I have a simple while loop to print even numbers from 0 to 10. I would expect this code to print only up to 10. But it goes up to 12. I can modify the code to check for i<10 instead of i<=10. But I do not understand why the while loop goes on to print 12.
I expect the below code to print up to 10. But it prints up to 12.
let i=0;
while (i<=10){
console.log(i);
i+=2;
}
2
Answers
it prints up to 12 because you set the codition i <= 10, i+=2. meaning as long as i is less than or equal to 10, it is going to add 2 to i. so if i is equal to 10, it is still going to add 2 to i. To achieve your desired result, i have update the code, see below:
The code works as expected. It doesn’t print 12.
Using Code Snippet allows you to verify the code easily.