Basic JavaScript - Iterate with JavaScript Do...While Loops

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

Link to the challenge:

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]

Hope this helps :slight_smile:

2 Likes

You can think of it as a conversation between your code and the computer like:

Your code: Hey computer, initialize a constant called myArray to an empty array.

Computer: OK. Done.

Your code: Cool. Also iniatilize a variable called i and assign it a value of 10.

Computer: OK. Done.

/* Computer sees an empty line and comment so it does nothing */

Code: Hey comp, can you do something else for me?

Computer: Whats that :wink: ?

Code: You see that constant you initialized for me, push the value of i to it and increment that i by one.

Computer: Done. I pushed 10 into myArray and added 1 to i. The value of i is now 11.

Code: Okay. Thanks. You can only keep pushing values of i into myArray while the value of i is less than 5.

Computer: Cool. I won’t be pushing again as i is now 11. At the moment, the constant myArray has [10] as it was the value I pushed.

/* Coversertion ends*/

As you may note, the do while loop ensures your code will run atleast once.
If you had a while loop, the array would be empty. That is:

// Setup
const myArray = [];
let i = 10;

// This code wont run as i > 5, so no value is pushed
while(i < 5){
  myArray.push(i);
  i++;
} 

Hope this helps!

Thank you all so much for taking time to explain me my stupid question. :smiling_face_with_tear:

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.