Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript loop doesn't work (learning JS)

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?)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading