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.
What JavaScript is telling you
ReferenceError: highscore is not definedJavaScript 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.
highscoreinstead ofhighScore. JavaScript cares about capitals, so these are two different names. - Wrong block. The variable was made with
letorconstinside{ }, and this line is outside them. - Used too early.
Cannot access 'score' before initializationmeans theletis 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.
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.
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);