Search code examples
javascriptecmascript-6varlet

How JS works for multiple variables with same name?


Why there is no Syntax error in the following code?

var num = 8;
var num = 10;
console.log(num) // 10

whereas

var num = 8;
let num = 10;
console.log(num) // already decleared error


Solution

  • The first case will be rendered as:

    var num;
    num = 8;
    num = 10;
    console.log(num); // output : 10
    

    The second case will be rendered as:

    var num;
    num = 8;
    let num; // throws Uncaught SyntaxError: Identifier 'num' has already been declared
    num = 10
    console.log(num);