Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Using let with for Loops

Why is 'i' worth 10 outside the loop ?

I know it's probably a very silly question but I struggle to understand, not the scope, the concept is clear, but why would the last console.log(i) prints 10 when it's previously left with a worth of 9 and nothing tells it to add anything further in this example (it's outside the loop already...), can someone please tell me why that is ? Thanks :)

var i; // i is declared in the global scope

for ( i = 0; i < 10; i++ ) { console.log(i); // logs the numbers 0 to 9 }

console.log(i); // 10

Mark Casavantes
Mark Casavantes
10,619 Points

Good Morning Outlandos,

In your for loop the numbers progress from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. 9<10 is true. When the program reaches i++ i is incremented one more time so the 9 becomes a 10. The next time the program loops 10<10 and the program stops. i remains equal to 10.

2 Answers

Because of the last alliteration of the loop (i) equal (9), but nine is less than (10) , so it goes to the loop body and update (i) to became (10).

Ok thanks a lot ! Silly I know, but it's been bugging me :)

It is okey, always ask about anything you don't fully understand because that will makes you a better developer.