Const variable

The variable fruit is assigned a different value on each iteration of the loop. The variable may be declared with the keywords: const , let , or var .

const fruits = ['oranges', 'apples', 'grapes']; for (const fruit of fruits) { console.log(fruit); }

How is this possible shouldn’t the fact that fruit was declared as a const make this impossible.for…of

In a for loop the variable is only alive during a single iteration, given that the flow exits the code block each time.

for (const a) {

}

a is local to the block.

2 Likes

Thank you for your swift response.
Follow up question

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

This doesn’t work though. Why?

Could I have been wrong? Well, partly, so. Consider,

const a = [1,2,3,4,5]
for (const x of a) {
  console.log(x)
}
1
2
3
4
5

In the above, the variable is being refreshed from the array. In your example, it is being incremented in the same context in which it is declared, so will raise an error.

Something to mark N. B. in your notes. Good that you tested this.

for (let i = 0; i < 3; i++) {
  console.log(i)
}
1 Like

Hello
Please I don’t really get the distinction you are trying to make. Yes it is taking it value from the array but isn’t that still a reassignment?
Thank you

A bit complicated to explain, but no. It is a new assignment with each iteration similar to calling a function over and over. A typical for loop is essentially syntactic sugar for a while loop:

for(let i = 0; i < 3; i++) {
  console.log(i);
}
// same as
let i = 0;
while(i < 3) {
  console.log(i);
  i++;
}
//same as:
let i = 0;
for(;i < 3;) {
  console.log(i);
  i++;
}

In all of these examples, the value i is assigned to is used to determine when to stop the loop. i is initially assigned, and re-assigned until our stop condition is reached. Since i is re-assigned after each iteration, const won’t work.

A for ... of loop is not a traditional for loop. It doesn’t iterate while a condition is true. The variable used is assigned to each element of the array (in @mtf’s example) in turn. The variable isn’t re-assigned. A new assignment is made for each element of the array.

2 Likes