Search code examples
javascriptfunctionecmascript-6var

Why can I declare a javascript var multiple times?


Why am I able to declare a var multiple times? I would expect an error.

This code raises an error:

let a = true;
let a = false;

Uncaught SyntaxError: Identifier 'a' has already been declared

Why doesn't this raise an error too?

var b = true;
var b = false;

Expected: Uncaught SyntaxError: Identifier 'b' has already been declared


Solution

  • It's because there's variable hoisting with var, but not with let (or const for that matter).

    So that means that each time you use var, it'll essentially cancel out the previous operations because to the JavaScript interpreter, your first code looks like:

    var b;
    b = true;
    b = false;
    

    But this doesn't work with let or const because let and const are block scoped, whereas var is function scoped.