The light in your room suddenly won't turn on. You don't pull the wiring out of the wall right away. You check one thing first, then the next:
- You press the switch once more. Is the light really off every time?
- You look at the light in another room. If that light works, the house's power is fine, and half of the possible causes are gone.
- You replace the bulb with a bulb you know is good.
Each step gives you one piece of evidence.
Debugging code works the same way. Debugging means finding out why code does something different from what you wanted, then fixing it. As with the light, you look for evidence at each step before you move on.
The code we're debugging
The processUsers function should return the result of three stages: keep only the active users (filter), turn each user into the text Name (age) (map), and sort those texts alphabetically (sort). For the users data below, the last line should print Andi (22),Budi (25),Dina (28).
function processUsers(users) {
const activeUsers = users.filter(u => u.active = true);
const formatted = activeUsers.map(u => u.nmae + " (" + u.age + ")");
formatted.sort();
}
const users = [
{ name: "Dina", age: 28, active: true },
{ name: "Budi", age: 25, active: true },
{ name: "Cici", age: 30, active: false },
{ name: "Andi", age: 22, active: true },
{ name: "Eka", age: 35, active: false }
];
const result = processUsers(users);
console.log(result.join(","));
A bug is a difference between what you want and what the code does. The code above has three bugs. We will find them one at a time in five steps.
Before you read on, guess: when this code runs, how many error messages appear, and on which line?
Step 1: reproduce it first
Reproducing means you can make the same bug appear every time, with clear steps. The report "it fails sometimes" can't be debugged yet. The report "run this file with the users data above, and a TypeError appears" can. Without a reproduction, you also can't prove that the bug is gone. That is why reproducing is the first step, before you change anything.
Step 2: read the error message
Run the code. Chrome's console (the browser panel that shows console.log text and errors) shows one red line:
TypeError: Cannot read properties of undefined (reading 'join')
TypeError: the kind of error. It means a value was used in a way its type doesn't allow.Cannot read properties of undefined: some code tried to read a property of the valueundefined.(reading 'join'): the property being read isjoin. To the right of the message, Chrome also shows the file name and the line number: theconsole.log(result.join(","))line.
So result holds undefined. Why? processUsers has no return, and a function without return always returns undefined. This is the first bug.
Notice two things. First, out of three bugs, only one produces an error message. The other two bugs produce no message at all: they only make the result wrong. Second, that message points at the last line, although the bug is inside processUsers. An error message points at where the program stopped, not necessarily where the mistake began.
Step 3: guess, then prove it
Add return formatted; at the end of the function and run it again. The error message is gone, but the output is still wrong:
undefined (22),undefined (25),undefined (28),undefined (30),undefined (35)
Now make a guess (a hypothesis) that you can check. Don't change code at random. The guess: "the property name is wrong", because every name shows as undefined. How to prove it: print one user with console.log.
console.log(activeUsers[0]); // {name: 'Dina', age: 28, active: true}
The property is called name, but the code reads u.nmae. A property that doesn't exist has the value undefined. When undefined is joined to text, the result is the word "undefined". The guess is proven: this is the second bug.
Step 4: narrow it down by splitting in half
The output in Step 3 has a second problem: it lists five people, but only three users are active. You don't need to read the code from the first line. Check the data at the midpoint. processUsers has three stages: filter, map, sort. Add a console.log after the first stage:
const activeUsers = users.filter(u => u.active = true);
console.log(activeUsers.length); // 5, should be 3
After filter, the data is already wrong: 5 users, and it should be 3. So map and sort are not the cause of the extra users, and the bug is in the first half. This method is called binary search debugging: check the midpoint, then continue in the half that has the problem. This way, code with 8 stages is checked in 3 logs, not 8.
The cause: u.active = true uses a single =. A single = assigns a value, it doesn't compare. That assignment always results in true, and filter keeps each user whose result is true, so it keeps them all. This is the third bug. Replace it with u.active === true.
Step 5: fix one thing, run it again
Change one thing, run the code, then look at the result. This table shows the console output as the fixes are added one at a time:
| Fix | Console output |
|---|---|
| none yet | TypeError: Cannot read properties of undefined (reading 'join') |
return formatted; |
undefined (22),undefined (25),undefined (28),undefined (30),undefined (35) |
u.active === true |
undefined (22),undefined (25),undefined (28) |
u.name |
Andi (22),Budi (25),Dina (28) |
Finally, verify (check again) with other data. Then you are sure that the function is right, and not only the result for the one example above. For data with Zaki (30, active), Ani (20, inactive) and Bimo (41, active), processUsers must return ["Bimo (41)", "Zaki (30)"]. For a list with no active users, the result must be an empty array, whose length is 0.
⚠️ Habits that make debugging take longer
- Changing code at random. If you make three changes at once and then the code works, you don't know which change fixed it. Doing that also often adds new bugs. One guess, one change, one run.
- Skipping the error message. The red line in the console is the clearest clue: the kind of error, the property being read, and the line number. Read the message to the end before you search the internet.
=inside a condition.u.active = truekeeps every user. It also changes the data: Cici and Eka becomeactive: true. To compare, use===.- Forgetting
return. A function withoutreturngivesundefined, and the error only appears on the line that uses that result.
💡 Rubber duck debugging
When you can't find the cause, explain the code line by line out loud, to a friend or to a rubber duck on your desk. While you say "and then this filter keeps the active users...", you often notice that the code as written doesn't do that. The duck doesn't need to answer.
TL;DR: Debugging means finding the cause of a bug (code doing something different from what you wanted), then fixing it. It has five steps, in order. (1) Reproduce: make the bug appear every time, with clear steps. (2) Read the error message. For example, TypeError: Cannot read properties of undefined (reading 'join') means some code read .join from the value undefined. (3) Make a guess about the cause, then prove it with console.log. (4) Narrow it down by splitting in half (binary search): print the data at the midpoint of the code, then continue in the half that is wrong. (5) Change one thing, run it again, then check with other data. An error message points at where the program stopped, not necessarily where the bug is. A function without return gives undefined. A single = assigns a value, while === compares.
⚡ Reproduce it first
Meaning: A bug is a difference between what you want and what the code does. Before you change anything, make that bug appear every time, with clear steps. That is reproducing. The report "it fails sometimes" can't be debugged yet (you can't look for its cause). Without a reproduction, you also can't prove that the bug is gone.
⚡ An error points at where it stopped
Write:
function processUsers(users) {
const activeUsers = users.filter(u => u.active = true);
const formatted = activeUsers.map(u => u.nmae + " (" + u.age + ")");
formatted.sort();
}
const result = processUsers(users);
console.log(result.join(","));
Guess first: users holds a list of users, and processUsers should return the names of the active users only. This code has three bugs. How many error messages appear when it runs?
Only one, on the last line: TypeError: Cannot read properties of undefined (reading 'join'). That message means the code read join from the value undefined. The cause is inside the function: there is no return, so result holds undefined. The other two bugs produce no message at all.
Meaning: An error message points at where the program stopped, not necessarily where the bug is. Here the program stopped on the last line, although the bug is inside processUsers.
⚡ Split it in half, log the middle
Write:
const activeUsers = users.filter(u => u.active = true);
console.log(activeUsers.length); // 5, should be 3
Meaning: processUsers has three stages: filter, map, sort. This log prints the data in the middle, after filter: there are 5 users, but only 3 are active. The data is already wrong after filter, so map and sort are not the cause of the extra users: the bug is in the first half. Checking the midpoint and then continuing in the wrong half is called binary search debugging. The cause is a single =: u.active = true assigns true to every user, so they all pass the filter. To compare, use ===.
⚡ Change one thing, run it again
Meaning: One guess, one change, one run. processUsers needs three fixes: return formatted; at the end of the function, u.active === true in place of u.active = true, and u.name (the data's property name) in place of u.nmae. After all three, the code prints Andi (22),Budi (25),Dina (28). Finally, check the function with other data.