Andrew Bullock
Andrew Bullock

Reputation: 37378

JavaScript const and let scoping syntax validity

Is the below valid JavaScript?

const x = 1;

if(x){
  const x = 2;
  console.log(x); // 2
}
console.log(x); // 1

As in, redefining x as a const (or let) within an inner block-scope?

Redefining as var isn't allowed, because this would be hoisted to the top scope and then conflict with original x declaration.

I think I'm correct here, right? Redefining in this way is allowed? Is this supported by all major JS engines?

Upvotes: 0

Views: 60

Answers (1)

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10384

Yes, the block is valid because of variable shadowing.

The second time you declare x, it gets declared in an inner scope and it will shadow all the variables with the same name in the outer scopes.

This allows you to give the name you prefer to your variables, without worrying if an external library or somewhere above there was a variable with the same name.

For example, you can declare let i for an index several times. If you couldn't, you should declare let i just once and then use i = ... all the other times.

But, if in the future you will decide that you won't need let i in the outer scope, you could delete it without thinking too much about consequences, and i = ... will become a global variable.

Upvotes: 2

Related Questions