Iterate with JavaScript Do...While Loops - Max value of i

Iterate with JavaScript Do...While Loops - Max value of i
0.0 0

#1

Why does while ( i < 11) return i as 11? Surely i <= 11 or i < 12 should result in i = 11; i < 11 should result in i = 10 as the maximum value ever reached?

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

// Only change code below this line.

do {
myArray.push(i);
i++;
} while (i < 11 );


**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36</code>.

**Link to the challenge:**
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do---while-loops

#2

This is because the condition is tested after the loop

In the final line of the last iteration of the loop you increment i and it is now 11

The condition is then tested: 11 < 11 is false, therefore the loop can not continue.

Therefore outside the loop, i is 11


#3

How confusing. So its value is 1 higher than in a for () loop, e.g

for (i = 1;  i < 10; i++) { 
    document.write(i); 
} 

// which returns up to 9, not 10

#4

mcpop999, nope! It’s just as confusing. What’s being asked is the value of i after you exit the loop. This will always be a value that makes the testing condition false, otherwise you wouldn’t have left the loop. In your example

for (i = 1;  i < 10; i++) { 
    
} 
document.write(i) // 10

If i < 10 was true after you’ve left the loop, then you should still be in the loop :slightly_smiling_face:


#5

Aha! Yes I see now! Been using them for ages, but never realised about the “after the loop has finished” value! Thanks @joker314 and @gebulmer.