Do while loop, why the while loop runs

Tell us what’s happening:
I am not understanding why the while loop is running? It seems that the do is causing the while to run at least one time. why is that? I thought it would hit the while loop see that it is false and exit. if I remove the do the while never runs? Could someone explain this to me please.

Your code so far


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

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36.

Challenge: Iterate with JavaScript Do…While Loops

Link to the challenge:

1 Like

The proper syntax of do...while:

do {
  // code
} while (condition);

And yes, the code inside will be executed at least once

1 Like

just to confirm the while loop will also run once? even though its false? In my code above I am getting a result [10,11]. it is running the while loop even though its false.

You have extra brackets at the end of the while statement. It will do it once no matter what, and if it’s true for the while condition it will keep doing what’s inside the do statement. Like what @snigo said, here is the syntax:

 do {
  // code
} while (condition);

Hope this helps.

if you don’t want to execute your code at least once, just use a while loop
a do…while will execute once and then check the condition