Home > database >  Why for of loop accepts the const keyword?
Why for of loop accepts the const keyword?

Time:12-13

A variable declared with the const keyword cannot be reinitialised. So, why the const keyword works for for of loop? For instance, if I have a loop like for(const x of array){...code here...}. Why it works instead of throwing an error as in the case of for(const x=0;x<array.length;x ){...code here...}?
Is it due to the fact that the latter mentioned for loop is reinitializing the value of variable x but, only declaring it once, in other words - the variable x is declared for the entire loop.
But, what about the for of loop? Is it redeclaring the value of x each time an iteration is done?
If not, then what factors make the former mentioned for of loop work?

CodePudding user response:

In the second example, you set const x to zero, and then attempt to alter the value with x . As the name implies, you cannot alter the value of a constant after it's declared. If you attempted to x inside the for/of loop it would also throw an error. Presumably, your for/of loop only reads the value of x and does not alter it (I say presumably because you did not share the code for this portion).

CodePudding user response:

The traditional for loop is a staple of many languages, and often takes a form like

for(x=0;x<array.length;x  )

This construct works due to the fact that the x is visible not only inside the loop, but also between iterations - so that the x works. JavaScript's for loops were designed to work similarly. A variable declared in the declaration of a for loop is visible throughout the loop body, and between iterations. (things get a bit stranger with let, but that's not really relevant to the issue here)

for..of is a different beast entirely. Despite it using the same word - for - as the for(;;) construct, it works quite differently. for..of invokes the iterator of the object for each iteration, and the values returned by the iterator aren't initialized before the loop - they're specific to each iteration, so having something like x wouldn't make much sense.

for..of, in psuedocode:

iterator = getIteratorFromObject();
loop {
  if (iterator.done) break;
  nextValue = iterator();
  // execute loop body with nextValue
}

The value returned by the iterator, when initialized with const (which has block scope, not function scope), makes sense to be scoped only to the block of that particular iteration. (If you tried to reassign the const identifier, just like in a traditional for loop, you'd get an error.)

Unlike a traditional for, there's not really any initial value to be initialized (other than the iterator, but the consumption of the iterator is abstracted behind the JavaScript engine).

  • Related