Tell us what’s happening:
Hi! I did understand the do… while loop. My question is about how does this loop even work?? i is 10, and in order for our while loop to start is i being smaller than 5 but it is really not. Because i is ten. Can you help me?
Your code so far
// Setup
const myArray = [];
let i = 10;
// Only change code below this line
do {
myArray.push(i);
i++;
} while (i < 5);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0
Challenge: Basic JavaScript - Iterate with JavaScript Do…While Loops
That’s the main difference between a do while compared to other loop.
Other form of looping check the condition first, before executing the body of the function.
A do while loop on the other hand executes the body, then check the condition.
So in our case execute the body and push i into the array.
Then check for the condition, since it’s false it exit the loop.
But at least the first execution is done, hence myArray = [10]
do while is an different looping method , its run once and check the condition after so it says
do {
myArray.push(i);
i++;
}
it means do myArray.push(i) , and then increment the i
and they check the condition
while (i < 5);
if this condition isnt true the loop is over at once , so the main thing is , do while is always run once before checking the condition no matter what , hope this help