Lesson 1.13: Debugging
A program almost never works the first time. Debugging is finding out why, and there's a method to it.
The idea
There are two kinds of bug:
- With an error: the program stops and the console says why, in red.
- Without an error: the program finishes, but the result is wrong.
For the first, you read the error. For the second, you look inside with console.log().
Reading an error
console.log(points);
Uncaught ReferenceError: points is not defined
at <anonymous>:1:13
It has three parts:
- The type:
ReferenceError. - The message:
points is not defined. - Where:
1:13, line 1, character 13.
The three most common
| Error | What it says | Usual cause |
|---|---|---|
SyntaxError | The code is badly written | A missing bracket, curly brace or quote |
ReferenceError | That name doesn't exist | A typo: name and Name are different |
TypeError | That value can't do that | Using something that is undefined |
No error, but wrong
This average should be 6.5:
const marks = [7, 4, 9, 6];
let sum = 0;
for (const mark of marks) {
sum = mark;
}
console.log(sum / marks.length);
1.5
A console.log() inside the loop shows what happens on each round. Separate the values with commas:
for (const mark of marks) {
sum = mark;
console.log("mark:", mark, "sum:", sum);
}
mark: 7 sum: 7
mark: 4 sum: 4
mark: 9 sum: 9
mark: 6 sum: 6
sum doesn't add up: each round replaces it. It has to be sum = sum + mark.
The method
- Read the first error, not the last.
- Go to the line it points to.
- If there's no error, add
console.log()to see the values. - Change one thing only and try again.
Try it
This program has two bugs. Paste it into the console and fix it one error at a time.
function greet(name) {
console.log("Hello, " + name;
}
Greet("Ana");
Show the solution
SyntaxError: the bracket ofconsole.log(is never closed. It becomesconsole.log("Hello, " + name);.- Once that's fixed, the second appears, a
ReferenceError: the function is calledgreetand it's used asGreet. Upper and lower case matter.
function greet(name) {
console.log("Hello, " + name);
}
greet("Ana");
The second bug didn't show until the first was fixed. That's normal: it's why you go one at a time.
Summary
- An error says what happened (type and message) and where (line).
- Without an error,
console.log()shows the values inside. - One at a time: the first error, a single fix, and try again.