Tell us what’s happening:
Describe your issue in detail here.
My doubt is in do…while loop.
Here take a look at my code.
I have written the incremental statement in “do” and it is incrementing to 11 so why while loop is also working once.
It should not work as i value became 11.
But I am getting output-like.
[10,11]
Can anyone tell me why this is happening? Your code so far
// Setup
const myArray = [];
let i = 10;
// Only change code below this line
do{
myArray.push(i);
i++;
}
while (i < 10) {
myArray.push(i);
i++;
}
console.log(myArray)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Iterate with JavaScript Do…While Loops
Simple Description of do…while is The do...while statements combo defines a code block to be executed once, and repeated as long as a condition is true .
The do...while is used when you want to run a code block at least one time.
In your case you push index two times first in while and second in do.
Take look of below code. Hope it help you to understand.
// Setup
const myArray = [];
let i = 10;
// Only change code below this line
do{
myArray.push(i);
i++;
}
while (i < 10);
console.log(myArray)
So I pushed index in do and it gets pushed in the array because code block runs a code at least one time then i value becomes 11 and I gave a condition (i < 10) so why and it is entering inside the while loop and and pushing 11 into the array.
As (i<10) is a false statement.
No matter what but it’s a nature of do…while loop.
It run once if condition is even false.
A do-while loop is a common control flow statement that executes its code block at least once, regardless of whether the loop condition is true or false. This behavior relies on the fact that the loop condition is evaluated at the end of each iteration. So, the first iteration always runs.
it runs the first iteration without checking the loop condition.