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.

Jaspreet Singh
  • 1,672
  • 1
  • 14
  • 21
  • Maybe there you can found an explanation: https://stackoverflow.com/questions/49148068/why-does-var-allow-duplicate-declaration-but-why-does-const-and-let-not-allow-du – Shidersz Feb 16 '19 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`. – Lennholm Feb 16 '19 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. – Jaspreet Singh Feb 16 '19 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. – A. Meshu Feb 16 '19 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? – Lennholm Feb 16 '19 at 19:54
  • @Lennholm I guess question was marked duplicate even before I could edit it, could you have a look at it now ? – Jaspreet Singh Feb 16 '19 at 20:00

0 Answers0