javascriptvariablessyntax-errordeclarationlet

Why does declaring a variable without a keyword result in a SyntaxError for var and const, but not for let in JavaScript?


Declaring variable in JS without keyword.

I get SyntaxError when I declare variable like var = 1 or const = 1. But I don't get this error when i declare like let = 1. Why is this happening?

var = 1; // Uncaught SyntaxError: Unexpected token '=' (at index.js:2:5)

const = 1; // Uncaught SyntaxError: Unexpected token '=' (at index.js:2:5)

let = 1; // NO ERROR.


Solution

  • var and const are reserved keywords ( can't be used as variable names), let in some environments is not a reserved keyword and in this situation, it is considered as a variable name.

    let = 1;
    
    console.log(let)