In JavaScript, you can do something like this:
const arr = [1, 2, 3, 4, 5];
for (const v of arr) console.log(v);
But in normal for loop, it gives a TypeError:
for (const i = 0; i < 5; i++) console.log(i);
// TypeError: Assignment to constant variable.
Shouldn't the for..of get an error as well?
No the for(...of...) loop won't get an error. Here is why:
In the second for loop, you are editing the constant variable which is NOT allowed. This throws a TypeError. In the first for loop, it doesn't matter what type of variable assignment you use. The variable (const,let, var, or no identifier) calls on the iterator which creates a sort of isolated temporary scope. This is why you can't access the variable outside of the for loop. For example:
const example = 1;
example = 2;
//TypeError
for (const someVar of Array(5)) someVar = 12;
//TypeError
{
const num = 200;
}
const num = 150;
//This is fine because of scope
In for...of create a loop iterating in the arr.
const x = [1,2,3,4,5,6]
for (const n of x) {
console.log(n)
}
It will iterate over the Object or Array, and
for (let i = 0; i < n;i++) {}
Here i = 0 then i = 1 then i = 2 and so on.
That is why you cannot use CONST because (you cannot reassign a value to const) i will be reassigned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With