Iterate with JavaScript While Loops (but only in a certain way?)

Iterate with JavaScript While Loops (but only in a certain way?)
0.0 0

#1

Tell us what’s happening:
I finished the challenge, but how come if I were to write:
while (i = 0; i <5; i++){
myArray.push(i);
}
It does not work. Is there a difference in how for loops and while loops react when I write the code this way compared to the correct answer below? Just curious.

Your code so far

// Setup
var myArray = [];

// Only change code below this line.
var i = 0; 
while ( i < 5){
  myArray.push(i);
   i++;
}

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:


#2

Think this post its quite explanatory what are the diffs between for and while and when to use them.


#3

you are using a while loop but with for loop format


#4

The for loop like this

for (let i = 0; i < 5; i++) {
  console.log(i);
}
/* console.log("outside", i); // FAILS - i out of scope */

is just shorthand for a while loop like this

let j = 0;
while (j < 5) {
  console.log(j);
  j++;
}
console.log("outside", j);

(…with at least one small difference. If using ES6 let instead of var to declare the for loop variable i is only in the scope of the block and not available outside of the block. Generally that is a good thing - variables in the outer global scope are prone to conflicts, especially i that gets used a lot.)

For loop also has all the parts - initialization, test and increment - all on one line. Easier to read, easier to maintain.

That said, sometimes the while loop just “reads” more clearly or just makes more sense. Not all loops are counting loops either.

while(more data in queue){
read data and do something with it
}

When to use one over the other will become more apparent as you progress through the challenges.