Skip to content

Chapter 11

Errors & Debugging

Your code will break. Constantly. This isn't a sign you're bad at programming - it's the job. The difference between a beginner and an expert isn't that the expert avoids errors; it's that they read them calmly and fix them quickly. Let's build that skill.

Reading an Error Message

When something goes wrong, JavaScript stops and prints a red message. It's trying to help. Take this mistake:

console.log(mesage); // we misspelled "message"

The Console shows something like:

Uncaught ReferenceError: mesage is not defined
    at <anonymous>:1:13

Don't skim past it - read it in three parts:

  • The type: ReferenceError - you used a name that doesn't exist.
  • The detail: mesage is not defined - it even tells you which name. (There's your typo.)
  • The location: 1:13 - line 1, character 13. It points you at the spot.

Most errors are this friendly once you actually read them. The type and the detail together usually tell you exactly what's wrong.

Errors You'll Meet Early

  • ReferenceError: x is not defined - a typo in a name, or you forgot to create the variable.
  • SyntaxError: Unexpected token - a missing bracket, quote, or comma. Count your ( ) and { } pairs.
  • TypeError: x is not a function - you called something with () that isn't a function, often a misspelled method name.
Tip
Copy the error message and paste it into a search engine. Someone has hit the exact same thing before - probably thousands of people. Searching error messages is a real, everyday programming skill, not cheating.

Debugging with console.log

Sometimes there's no error - the program just gives the wrong answer. This is a bug, and your best tool for hunting it is one you already know: console.log. Sprinkle it around to see what your values actually are at each step:

function averageOf(numbers) {
  let sum = 0;
  for (const n of numbers) {
    sum = sum + n;
  }
  return sum / numbers.length;
}

console.log(averageOf([10, 20, 30])); // expected 20

Suppose that returned something odd. Add logs to watch the values evolve:

function averageOf(numbers) {
  let sum = 0;
  for (const n of numbers) {
    sum = sum + n;
    console.log("added", n, "-> sum is now", sum);
  }
  console.log("final sum:", sum, "count:", numbers.length);
  return sum / numbers.length;
}

Now you can see each step. Was a value not what you expected? Did the loop run the right number of times? Seeing the real values almost always reveals where reality diverged from your assumption - and that spot is your bug.

The Debugging Mindset

When stuck, resist the urge to change things randomly. Instead:

  • State what you expected to happen and what actually happened.
  • Add logs to find the exact line where they first differ.
  • Change one thing, run again, and see if it moved.

Programming is mostly this loop: try, observe, adjust. Get comfortable with it and errors stop being scary - they become directions.