Coming from a PHP background, I’m now learning JS, and I don’t understand why this piece of code doesn’t work:
let i = 0;
let arr = [];
while(i < 8){
arr[i] = i;
i++;
}
for(i = 0; arr[i]; i++) {
console.log("Result:", arr[i]);
}
From my point of view, this code is logic:
- I declare all my variables
- I put some random values in the array (just to fill it with something)
- I want to console.log each element of the array while the condition is true
I know that i equals to 8 after the while loop, but even an "i=0" before the for doesn’t solve the issue (BTW why the i = 0 inside the for initialisation doesn’t set it to 0?)
Can someone explain me what breaks the code?
>Solution :
for loops run until the condition is not true.
The first time around the loop i is 0 so arr[i] is arr[0] which you’ve populated with a 0.
0 is a false value, so the condition is false and the loop ends before the first iteration.
You probably want the condition to be i < arr.length.