0

I have heard about shadowing in JS. My question is why can't we shadow a let variable present in global scope with a var variable present inside a block . Eg->

let a =100;
{
 var a =100;
 console.log(a);
}
  • Output:-Uncaught SyntaxError: Identifier 'a' has already been declared.

This question came to my mind because I studied that let and var variables are present in different memory locations. So according to me this shouldn't be a problem.

And if there is a problem then why the below code is working

var a = 100;
{
let a=10;
console.log(a);
}

Output:- 10

Please provide a detailed answer explaining about the exceution context and variable environment in each case .

anany
  • 1
  • 7
  • `var` declarations are interpreted as if they appeared at the top of the closest enclosing `function` or global/module scope. You've got the functionality of `let` and `var` backwards. – Pointy Mar 05 '21 at 17:36
  • Also "present in different memory locations" is not a correct characterization of the difference between `let` and `var`. – Pointy Mar 05 '21 at 17:37
  • @pointy that for giving a vague explanation of how let and var works :) – anany Mar 05 '21 at 17:41
  • @pointy I want to know what happens under the hood . Why is there a Block memory space and a Global memory space in chrome debugger . And why exactly it is causing an issue . :) – anany Mar 05 '21 at 17:43
  • Read the linked duplicate question. There's a huge amount of information there. – Pointy Mar 05 '21 at 17:46

0 Answers0