Skip to content
Programming contents

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

JavaScript
console.log(points);
Console
Uncaught ReferenceError: points is not defined
    at <anonymous>:1:13

It has three parts:

  1. The type: ReferenceError.
  2. The message: points is not defined.
  3. Where: 1:13, line 1, character 13.

The three most common

ErrorWhat it saysUsual cause
SyntaxErrorThe code is badly writtenA missing bracket, curly brace or quote
ReferenceErrorThat name doesn't existA typo: name and Name are different
TypeErrorThat value can't do thatUsing something that is undefined

No error, but wrong

This average should be 6.5:

JavaScript
const marks = [7, 4, 9, 6];
let sum = 0;

for (const mark of marks) {
  sum = mark;
}

console.log(sum / marks.length);
Console
1.5

A console.log() inside the loop shows what happens on each round. Separate the values with commas:

JavaScript
for (const mark of marks) {
  sum = mark;
  console.log("mark:", mark, "sum:", sum);
}
Console
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

  1. Read the first error, not the last.
  2. Go to the line it points to.
  3. If there's no error, add console.log() to see the values.
  4. Change one thing only and try again.

Try it

Exercise

This program has two bugs. Paste it into the console and fix it one error at a time.

JavaScript
function greet(name) {
  console.log("Hello, " + name;
}

Greet("Ana");
Show the solution
  1. SyntaxError: the bracket of console.log( is never closed. It becomes console.log("Hello, " + name);.
  2. Once that's fixed, the second appears, a ReferenceError: the function is called greet and it's used as Greet. Upper and lower case matter.
JavaScript
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.