3

I have recently noticed below code works

var x = 10;
var x = 20;

on the other side below throws error for redeclaration of same variable

let x = 10;
let x = 20;

Below link gives insights by keeping functional scope vs block scope as reference.

Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?

var declarations are executed in execution context, a entry in variableObject is created and re-declarations points to same entry/variable again and again in case of duplication.

How is this different in case of let ?

Isn't it still executed in execution context ?

Some good links or detailed explanation would be appreciated.

6
  • Maybe there you can found an explanation: stackoverflow.com/questions/49148068/… Commented Feb 16, 2019 at 19:37
  • 1
    Because that was a mistake from the beginning with var but it couldn't be changed for compatibility reasons. let and const are basically the fix for var. Commented Feb 16, 2019 at 19:38
  • @Lennholm yes, ideally let behaves in the correct manner but not var. I agree with you on this. Still more interested in how engines sees it and differentiates in execution of both. Commented Feb 16, 2019 at 19:40
  • It's because var is function scoped and let is block scoped,, so a variable declared with var is defined throughout the program while let not. Commented Feb 16, 2019 at 19:42
  • 1
    @JaspreetSingh The specification dictates it that way. Are you asking why JS engines adhere to the specification or how engines implement it internally? Commented Feb 16, 2019 at 19:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.