Iterate with JavaScript Do...While Loops

Iterate with JavaScript Do...While Loops
0.0 0

#1

Tell us what’s happening:
So I was able to solve this problem via trial and error but I don’t get it. I thought the do function will execute no matter what. Then the while loop would only execute when the condition is true. Why does the while loop execute when var i > 5.

Shouldn’t myArray = [10] and var i remain 10? and never push again since the while loop condition fails?

Tl;Dr why does the while loop execute when the condition isn’t meet?

Your code so far


// Setup
var myArray = [];
var i = 10;

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do---while-loops/


#2

All of your logic goes inside of the do portion. only place the condition in the while.

var myArray = [];
var i = 10;

do {
myArray.push(i)
i++
} while (i < 5)

#3

@randallwhitlock is correct so I won’t repeat what he said

I think the point they were demonstrating is that a do…while loop will always execute at least one time even if the condition is false because the condition is tested after the first iteration.

In this case i was not <5 but your loop executed the first time anyways.