-7

In the code below, is ele available only for an individual iteration of the loop?

for (var i=0; i<3; i++){
  const ele = i
  console.log(ele)
}

I'm thinking this should be the case, otherwise there will be a

Syntax Error: Identifier 'ele' has already been declared

every time the loop iterates after the very first time.

I could not find a way to confirm this using console.log(), so looking for a concrete answer.

EDIT: To clarify, I understand that ele is valid within the for loop only. My question is specifically if the scope is ' reinstantiated' every iteration of this loop or not. It definitely looks like it, but I haven't heard or read that explicitly anywhere yet.

Stacker
  • 37
  • 4
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const: _"Constants are block-scoped, much like variables declared using the let keyword."_ – CBroe Feb 08 '22 at 13:09
  • You example code runs fine, and shows that `ele` is updated on each iteration, not just the first. And each iteration will get a new instance of `ele` as a new block is created each loop. – Keith Feb 08 '22 at 13:15
  • https://onecompiler.com/javascript/3xssdrf4d works fine – Ahmed Ali Feb 08 '22 at 13:17
  • Just to confirm what block scoping is, this code is totally valid, `{const x=1; {const x=2; { const x = 3; }}}` as each `const x` is in a separate block scope. IOW whenever you see code inside `{}` including for loops, you have a new block scope. – Keith Feb 08 '22 at 13:19

1 Answers1

-3

why do not directly use console.log(i) ?

howei think you should try to use var or let instead of const

ItzDragon
  • 1
  • 2