Home > Blockchain >  JavaScript loop doesn't work (learning JS)
JavaScript loop doesn't work (learning JS)

Time:12-21

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:

  1. I declare all my variables
  2. I put some random values in the array (just to fill it with something)
  3. 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?

CodePudding user response:

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.

CodePudding user response:

In your first look you set arr[i] = i. In the second loop your condition is arr[i], and on the first iteration i = 0, which means arr[i] is 0 which evaluates to false causing your loop to exit.

CodePudding user response:

for loop condition is not correct, if you would like to console.log all values of array, you can use length() property to check the length if array and check in the for loop condition.

let i = 0;
let arr = [];

while(i < 8){
  arr[i] = i;
  i  ;
}

for(i = 0; i < arr.length; i  ) {
  console.log("Result:", arr[i]);
}

  • Related