-6

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.

4
  • 2
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…: "Constants are block-scoped, much like variables declared using the let keyword." Commented Feb 8, 2022 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. Commented Feb 8, 2022 at 13:15
  • onecompiler.com/javascript/3xssdrf4d works fine Commented Feb 8, 2022 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. Commented Feb 8, 2022 at 13:19

1 Answer 1

-3

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

it's bad practice to use var in a loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.