JavaScript throws syntax error on the word "class" [duplicate]

10 hours ago 2
ARTICLE AD BOX

Welcome to JavaScript! You've stumbled onto something every beginner hits eventually: reserved words.

class is a keyword that JavaScript itself uses for defining classes. Because the language reserves it for its own use, you can't use it as a variable name. That's why your code breaks the moment the parser sees let class = ...

This is also why your experiments behaved the way they did:

Class (capital C) worked because JavaScript is case-sensitive, and only the lowercase class is reserved.

myclass worked because it's just a regular identifier that happens to contain the word.

"class" in quotes became a string literal, which is valid syntax but meant something completely different (hence the new error).

The fix

Just rename the variable to something that isn't reserved:

let teacher = "Mr. Henderson"; let room = 204; let subject = "Biology"; // <-- renamed from `class` let period = 3; console.log(teacher + " teaches " + subject + " in room " + room);

Other reserved words to avoid

Some common ones that trip beginners up: class, function, return, if, else, for, while, let, const, var, new, this, super, import, export, default, delete, typeof, instanceof, null, true, false.

The full list is on MDN's reserved words page if you're curious.

Read Entire Article