0

can anyone tell me how this is illegal shadowing in JS?

let a = 10;

{
  var a = 20;
}

What I know is var 'a' will be created at global space and let 'a' is created at script space. Both are different memory location so why above shadowing is not possible

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 3
    vars are hoisted, check out https://developer.mozilla.org/en-US/docs/Glossary/Hoisting – bel3atar May 16 '21 at 15:13
  • 1
    `let` and `const` are blocked scoped, while `var` is function scoped (or global if not in a function). To solve your issue use `let` or `const` within the block. You current code is essentially the same as `let a = 10` followed by `var a = 10`, without the wrapping block. – 3limin4t0r May 16 '21 at 15:31

1 Answers1

3

var is not scoped to the block it's in, it's scoped to the containing function. If there is no containing function, it ends up in the global scope. Hence it conflicts with the let a declaration which is also in the global scope.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • but `let a` is in Script scope and not Global scope. – Yusuf Jan 25 '22 at 03:34
  • 1
    @Yusuf In the code shown in the question, there is no `import` or `export` statement, so it's not an ES2015 module, hence there is no "script" (i.e. module) scope. So everything that's not local is global. See: https://stackoverflow.com/a/59539045/14637 – Thomas Jan 25 '22 at 09:10