AI-Powered Code Review Tool
Build an Intelligent Code Reviewer with AI
By AI Learning Assistant · OpenAI API · Prompt Engineering · Code Quality
🤖 AI-POWERED LESSON
This article is paired with a live AI session. You will learn to build a tool that uses AI to review JavaScript code — the same pattern used by professional developers to automate code quality checks. Every code block includes detailed line-by-line comments.
Imagine having a senior developer sitting next to you, reading every line of code you write, and giving you thoughtful feedback on what works well and what could be better. That's exactly what we're building today an AI-powered code review tool that analyzes JavaScript code and provides professional feedback.
This is where AI truly shines: not replacing developers, but augmenting them. The AI acts as a tireless code reviewer that never gets tired, never misses a semicolon, and always gives constructive feedback. You'll learn how to use the OpenAI API, craft effective system prompts, and understand the art of prompt engineering.
We will cover setting up the OpenAI Node.js SDK, designing a system prompt for code review, passing user code as a string, parsing AI responses, and the critical skill of prompt engineering how to phrase instructions so the AI gives you exactly what you need.
What is Prompt Engineering?
THE ART OF TALKING TO AI · SYSTEM VS USER MESSAGES
Prompt engineering is the skill of designing instructions that get the best possible output from an AI model. It's like learning to ask the right questions. A vague prompt gives vague answers. A specific, well-structured prompt gives professional, actionable feedback.
In the OpenAI API, you have two types of messages: system (sets the AI's persona and behavior) and user (the specific request). The system prompt is where you define the role: "You are a senior JavaScript developer..." This context dramatically improves the quality of responses.
🎯 PROMPT ENGINEERING TIPS
1. Define a persona — "You are a senior JavaScript developer" sets expectations. 2. Structure the output Asking for specific sections (strengths, improvements, refactored code) ensures consistent responses. 3. Be instructive "Be constructive, kind, and educational" shapes the tone. 4. Use examples Showing the format you want improves results dramatically.
Build the Code Review Tool
OPENAI API · SYSTEM PROMPT · ASYNC/AWAIT
📜 CODE BLOCK 1: Complete AI Code Review Tool (with line-by-line comments)
// ============================================ // AI-POWERED CODE REVIEW TOOL // ============================================ // STEP 1: Install the OpenAI package first // $ npm install openai // STEP 2: Import the OpenAI SDK // WHY: This gives us access to GPT models via API const OpenAI = require("openai"); // STEP 3: Initialize the client with your API key // WHY: Authentication — proves you have access to OpenAI // HOW: Get your key from https://platform.openai.com/api-keys // NEVER hardcode keys in production! Use environment variables. const client = new OpenAI({ apiKey: "YOUR_API_KEY_HERE" // Replace with your actual key }); // ============================================ // THE CODE REVIEW FUNCTION // ============================================ // WHY: async because we're waiting for the API response // WHY: Takes code as a string, returns AI review as a string async function reviewCode(code) { // WHY: Call the chat completion API // HOW: We specify model (gpt-3.5-turbo is fast and affordable) // messages: array of conversation turns const response = await client.chat.completions.create({ model: "gpt-3.5-turbo", // Good balance of quality and cost messages: [ { // SYSTEM PROMPT — This sets the AI's persona and behavior // WHY: The system message defines WHO the AI is acting as // A good system prompt dramatically improves response quality role: "system", content: `You are a senior JavaScript developer with 10 years of experience. Your job is to review code written by junior developers. For every code review, you must provide: 1. WHAT IT DOES WELL — Two to three specific strengths 2. WHAT CAN BE IMPROVED — Three to five actionable suggestions 3. A BETTER VERSION — Rewrite the code following best practices Be constructive, kind, and educational. Explain the WHY behind each suggestion.` }, { // USER PROMPT — The specific code to review // WHY: Template literals let us inject the user's code role: "user", content: `Please review this JavaScript code thoughtfully:\n\n${code}` } ] }); // WHY: Extract the AI's response from the API response object return response.choices[0].message.content; } // ============================================ // TEST THE TOOL — Example code that needs improvement // ============================================ // WHY: This code has several common issues: // - Uses 'var' instead of const/let // - Inconsistent spacing // - Missing semicolon consistency // - Could be written more concisely const myCode = `function add(a, b) { var result = a + b return result }`; // WHY: Call the review function and print the result // .then() handles the Promise returned by async function reviewCode(myCode) .then(review => console.log(review)) .catch(error => console.error("Review failed:", error));
📜 CODE BLOCK 2: Production-Ready Version (with .env)
// PRODUCTION VERSION — Uses environment variables // Never hardcode API keys in your source code! // Install dotenv: npm install dotenv // Create a .env file with: OPENAI_API_KEY=your_key_here require("dotenv").config(); const OpenAI = require("openai"); const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); async function reviewCode(code, options = {}) { const { model = "gpt-3.5-turbo", temperature = 0.5 // Lower = more focused, consistent } = options; const response = await client.chat.completions.create({ model: model, temperature: temperature, messages: [ { role: "system", content: `You are a senior JavaScript developer. Review the code and provide: 1. Strengths (what works well) 2. Improvements (specific actionable feedback) 3. Refactored version with best practices` }, { role: "user", content: `Review this code:\n\n${code}` } ] }); return response.choices[0].message.content; }
LIVE AI LEARNING SESSION
Ask your AI assistant this question ↓
💬 YOU ASK THE AI:
"What are the most common JavaScript code quality issues beginners make? List the top 10 with examples and how to fix them."
🤖 AI RESPONDS (Top 10 Beginner JavaScript Issues):
1. Using 'var' instead of 'const' and 'let'
❌ var x = 10;
✅ const x = 10; // or let x = 10;
Why: var has function scope and can be redeclared, causing bugs. const/let have block scope.2. Not handling errors in async code
❌ fetch(url).then(res => res.json())
✅ fetch(url).then(res => res.json()).catch(err => console.error(err))
Why: Unhandled promise rejections crash your app silently.3. Using == instead of ===
❌ if (5 == "5") → true (coercion)
✅ if (5 === "5") → false (strict equality)
Why: == performs type coercion leading to unexpected results.4. Mutating objects when you should copy them
❌ const newObj = obj; newObj.name = "changed"; // mutates original!
✅ const newObj = { ...obj, name: "changed" };
Why: Objects are references; mutations affect all references.5. Forgetting to await inside async functions
❌ async function getData() { return fetch(url); } // returns Promise
✅ async function getData() { const res = await fetch(url); return res.json(); }
Why: Without await, you get a Promise object instead of the actual value.6. Not using default parameters
❌ function greet(name) { name = name || "Guest"; }
✅ function greet(name = "Guest") { }
Why: Default parameters are cleaner and handle falsy values correctly.7. Accessing undefined properties (no optional chaining)
❌ const city = user.address.city; // TypeError if address missing
✅ const city = user?.address?.city ?? "Unknown";
Why: Optional chaining prevents runtime crashes on missing properties.8. Creating memory leaks with event listeners
❌ element.addEventListener("click", () => {}) // never removed
✅ element.removeEventListener("click", handler);
Why: Unremoved listeners accumulate memory in SPAs.9. Inefficient DOM manipulation in loops
❌ for(let i=0;i<100;i++) { container.innerHTML += ""+i+""; }
✅ let html = ""; for(let i=0;i<100;i++) { html += `${i}`; } container.innerHTML = html;
Why: DOM reflows on every iteration; batch updates are much faster.10. Not using meaningful variable names
❌ let d = new Date(); let u = getData();
✅ let currentDate = new Date(); let userData = getUserData();
Why: Code is read 10x more than written. Clear names prevent bugs.📝 MY NOTE — IN MY OWN WORDS
Building this AI code reviewer was mind-blowing. I learned that prompt engineering is not just asking — it's about giving the AI a role, setting expectations, and structuring the output. The system prompt is like giving someone a job description before they start. I now understand why the AI gave better reviews when I added "be constructive and educational" — the tone matters! The top 10 issues list showed me my own bad habits (I still use == sometimes). I am going to run all my future code through this AI reviewer before asking for human feedback. This tool will make me a better developer.
Bad Prompt vs Good Prompt
Aspect Bad Prompt Good Prompt System Role "Review this code" "You are a senior JS developer with 10 years experience..." Output Structure No structure specified "Provide: 1) Strengths 2) Improvements 3) Refactored code" Tone Not specified "Be constructive, kind, educational" Result Vague, generic feedback Actionable, detailed, professional 🤖 HOW AI ACCELERATES THIS TOPIC
Ask AI: "Improve this system prompt to get more detailed code reviews." Paste your prompt and get professional improvements.
Ask: "What are the best practices for storing and managing API keys in a Node.js application?" Learn about .env, secrets managers, and security.
Ask: "Design a prompt that makes the AI check for security vulnerabilities in JavaScript code." Extend your tool for security auditing.
AI-Assisted JavaScript Learning · Build an AI Code Reviewer · Master Prompt Engineering
Learn this with a real instructor
Free lessons take you a long way on your own. The full programmes add live classes, assignments, Skill Points and a certificate — built for African students.