0

Say I have this:

for(const v of [1,2,3]){
  console.log(v);
}

const v = 5;
console.log(v);

does that create a unique local scope for v just like let would? The above runs fine.

This fails, as we might expected given the above:

for(const v of [1,2,3]){
  console.log(v);
}

console.log(v);  // v is not defined, but if we used var instead of const, it would be defined
andyrandy
  • 72,880
  • 8
  • 113
  • 130
  • 4
    Yes, the block scoping rules are identical for `const` and `let` – CertainPerformance Dec 06 '18 at 08:06
  • 2
    You cannot declare for example, but works same way (except you cannot reassign to that variable) `for (const i = 0 ; i < ...; i++) { ... }` – Nika Dec 06 '18 at 08:11
  • 3
    Before posting a question, do a proper research (as you are supposed to), and it would have given you the answer: https://www.google.com/search?q=const+local+scope – Asons Dec 06 '18 at 08:19

2 Answers2

2

Yes, it does - const is a block-scope constant declaration keyword, meaning that in your second example, v is only defined within the {} of the for loop. Changing it to var - which has function scope (it exists only within its enclosing function) - means that it's accessible outside of a for loop (because it's not a function).

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

Yes, bot let and const are block scoped. Refer to this for a clear picture on scopes of let and const.