Every programmer writes bugs; good programmers find them quickly. Debugging is the skill of working out why code does not do what you expect. JavaScript gives you two main tools: the console object, for printing values while the program runs, and the browser’s DevTools debugger, for pausing the program and examining it line by line. This lesson covers both, plus a simple method for hunting down any bug.
In this lesson you will learn
- The most useful
consolemethods beyondconsole.log - Tracing a bug step by step with logs and assertions
- Reading error messages and stack traces
- Breakpoints and the
debuggerstatement in DevTools - A repeatable method for fixing bugs
You should know functions, loops and error handling.
The console Toolbox
"use strict";
// console.log prints any values, separated by spaces
const student = { name: "Rina", roll: 7, marks: [78, 91, 85] };
console.log("Student:", student.name, "Roll:", student.roll);
// Labels in an object make several values easy to read
const total = student.marks.reduce((a, b) => a + b, 0);
console.log({ total, average: total / student.marks.length });
// console.table shows arrays of objects as a table
console.table([
{ subject: "Maths", mark: 78 },
{ subject: "Physics", mark: 91 },
]);
// Grouping related messages
console.group("Checking marks");
console.log("Highest:", Math.max(...student.marks));
console.log("Lowest:", Math.min(...student.marks));
console.groupEnd();
// Counting how often something happens
for (const m of student.marks) {
if (m >= 80) console.count("A grade");
}
// console.assert prints only when the condition is false
console.assert(total === 254, "total should be 254");
console.assert(total > 300, "total is not above 300");
// Warnings and errors (in a browser they appear yellow and red)
console.warn("Attendance below 75%");
console.error("Could not load results");
Output
Student: Rina Roll: 7
{ total: 254, average: 84.66666666666667 }
┌─────────┬───────────┬──────┐
│ (index) │ subject │ mark │
├─────────┼───────────┼──────┤
│ 0 │ 'Maths' │ 78 │
│ 1 │ 'Physics' │ 91 │
└─────────┴───────────┴──────┘
Checking marks
Highest: 91
Lowest: 78
A grade: 1
A grade: 2
Assertion failed: total is not above 300
Attendance below 75%
Could not load results
console.logaccepts any number of values. Wrapping variables in braces, as inconsole.log({ total, average }), prints their names as well as their values, so you never mix them up.console.tableturns an array of objects into a table: much easier to read than nested brackets.console.groupandconsole.groupEndindent related messages. In the browser, groups can be collapsed.console.count(label)counts how many times a line runs. It is handy for checking whether a loop or event handler fires as often as you expect.console.assert(condition, message)prints only when the condition is false. The first assertion passed silently; the second printed its message.console.warnandconsole.errorstand out in yellow and red in the browser, and DevTools can filter by these levels.console.time("x")andconsole.timeEnd("x")measure how long code takes.
Tracing a Real Bug
"use strict";
// A buggy function: it should return the average of the marks
function averageBuggy(marks) {
let sum = 0;
for (let i = 1; i <= marks.length; i++) { // two mistakes hide here
sum += marks[i];
}
return sum / marks.length;
}
console.log("Buggy result:", averageBuggy([60, 70, 80]));
// Step 1: log what the loop actually sees
function averageTraced(marks) {
let sum = 0;
for (let i = 1; i <= marks.length; i++) {
console.log(" i =", i, "marks[i] =", marks[i], "sum =", sum);
sum += marks[i];
}
return sum / marks.length;
}
averageTraced([60, 70, 80]);
// Step 2: fix the cause (indexes run from 0 to length - 1) and check it
function average(marks) {
let sum = 0;
for (let i = 0; i < marks.length; i++) {
sum += marks[i];
}
return sum / marks.length;
}
console.log("Fixed result:", average([60, 70, 80]));
console.assert(average([60, 70, 80]) === 70, "average is wrong");
// Errors carry a stack trace that names the function and line
function readMark(marks, i) {
if (i >= marks.length) throw new RangeError("No mark at index " + i);
return marks[i];
}
try {
readMark([60, 70], 5);
} catch (err) {
console.log(err.name + ": " + err.message);
console.log("First stack line:", err.stack.split("\n")[1].trim().split(" (")[0]);
}
Output
Buggy result: NaN
i = 1 marks[i] = 70 sum = 0
i = 2 marks[i] = 80 sum = 70
i = 3 marks[i] = undefined sum = 150
Fixed result: 70
RangeError: No mark at index 5
First stack line: at readMark
- The buggy function returns
NaN(“Not a Number”). That tells us anundefinedcrept into the arithmetic somewhere, but not where. - Logging inside the loop shows everything at once: the loop starts at index 1, so it skips 60, and it continues to index 3, which does not exist and gives
undefined. Adding a number toundefinedgivesNaN. - The fix uses the standard loop
for (let i = 0; i < marks.length; i++). An assertion then confirms the expected answer. - When something throws, the error object has a
name, amessageand astack. The stack lists the chain of function calls, most recent first, with file names and line numbers, so it points straight at the problem.
Using the Browser Debugger
Logs show what you thought to print. The debugger shows everything. Open DevTools with F12 (or Ctrl+Shift+I; Cmd+Option+I on a Mac) and go to the Sources panel.
- Set a breakpoint by clicking a line number. When the code reaches that line, it pauses.
- Or write
debugger;in your code. While DevTools is open, the program pauses there. - While paused, hover over any variable to see its value, or look in the Scope section for all of them.
- Use the step buttons: Step over (run the next line), Step into (enter a function call) and Step out (finish the current function).
- Add a Watch expression, such as
sum / marks.length, to see it update at every step. - Conditional breakpoints (right-click a line number) pause only when a condition is true, for example
i === 3.
Remove debugger statements and stray console.log lines before you publish your code.
A Method for Any Bug
| Step | What to do |
|---|---|
| 1. Reproduce | Find exact steps or inputs that make the bug happen every time. |
| 2. Read the error | Note the error type, message and the first stack line from your code. |
| 3. Narrow it down | Log or pause halfway through. Is the value already wrong there? Then the bug is earlier; if not, later. |
| 4. Fix the cause | Correct the real mistake, not just the symptom. |
| 5. Check | Re-run the original steps and a few edge cases, such as an empty array. |
Common Mistakes
- Guessing and changing code at random instead of looking at the actual values.
- Ignoring the error message, which usually names the line and the problem.
- Logging an object and reading it later. Browser consoles can show the object’s current state, not its state when logged. Log
JSON.stringify(obj)or a copy if it matters. - Leaving debug logs in finished code.
Practice Exercises
Exercise 1. Use console.time to measure how long it takes to add up the numbers from 1 to 1,000,000.
Show answer
console.time("sum");
let total = 0;
for (let i = 1; i <= 1000000; i++) total += i;
console.timeEnd("sum"); // prints something like "sum: 4.2ms"
console.log(total); // 500000500000
Exercise 2. This function should return the largest number, but largest([-5, -2, -9]) returns 0. Find the bug.
function largest(nums) {
let max = 0;
for (const n of nums) if (n > max) max = n;
return max;
}
Show answer
Starting max at 0 means no negative number is ever larger. Start with the first element instead: let max = nums[0]; (or use Math.max(...nums)).
Frequently Asked Questions
Can I debug Node.js programs too?
Yes. Run node –inspect-brk app.js and open chrome://inspect in Chrome, or use the built-in debugger in an editor such as VS Code, which lets you set breakpoints directly in your files.
Why does my error say “undefined is not a function” or “cannot read properties of undefined”?
You used a value that is undefined as if it were a function or an object. Common causes are a misspelled name, a missing return statement, or data that has not loaded yet. Log the value just before the failing line to see which.
Summary
console.log,table,group,count,assertandtimereveal what your code is doing.- Error messages and stack traces point to where things went wrong.
- Breakpoints and
debuggerpause the program so you can inspect every variable. - Reproduce, read, narrow down, fix the cause, then check.
