Brainlag
  1. Library
  2. Debugging
  3. Web

ReferenceErrorWhat is a ReferenceError?

JavaScript stops with a ReferenceError when a line uses a name that does not exist where it runs. Usually a typo, a capital letter or a name used outside its block.

Web5 min

What JavaScript is telling you

Output
ReferenceError: highscore is not defined

JavaScript reads that as: "this line uses highscore, and there is no variable with that name here". It only knows names that were made with let, const, function or as a parameter, in this block or one around it.

The usual reasons:

  • A typo. highscore instead of highScore. JavaScript cares about capitals, so these are two different names.
  • Wrong block. The variable was made with let or const inside { }, and this line is outside them.
  • Used too early. Cannot access 'score' before initialization means the let is further down than the line using it.

How to find it

Read the error's last line first: it names the missing variable and the line it was used on. Search your code for where that name is created. Created nowhere? Look for a near-miss spelling. Created inside a loop, an if or another function? Move the let or const up above those braces.

Run it: one capital letter

Press Run and read the error from the bottom up.

main.js to run
const highScore = 4200;
const thisRun = 3900;

if (thisRun > highscore) {
  console.log("New record!");
}

The streak that is never defined

This should print Best streak: 4. Run it, read the error, then fix it.

exercise_1.js to run
const games = ["W", "W", "L", "W", "W", "W", "W", "L"];
let current = 0;
for (const g of games) {
  let best = 0;
  if (g === "W") {
    current = current + 1;
    if (current > best) best = current;
  } else {
    curent = 0;
  }
}
console.log("Best streak: " + best);

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.