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 trialhannah4
17,400 PointsWhy 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
2 Answers
jhon white
20,006 PointsBecause 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).
hannah4
17,400 PointsOk thanks a lot ! Silly I know, but it's been bugging me :)
jhon white
20,006 PointsIt is okey, always ask about anything you don't fully understand because that will makes you a better developer.
Mark Casavantes
10,619 PointsMark Casavantes
10,619 PointsGood 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.