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 For loops question about the first value being logged

I'm having a problem wrapping my head around why '5' gets logged first ... My thinking is that you meet the condition so then +5 is added to i which then = 10.

I can't understand why 5 is the first number logged and not 10

var text = ' ';

for (let i = 5; i <= 50; i += 5){
   text += i + ' ';
}

result when logged/print/write = 

`5 10 15 20 25 30 35 40 45 50 `

1 Answer

Take into account the structure of this loop:

for ([initialization]; [condition]; [final-expression]) {
   statement;
}

This kind of loop always runs first with the initialization value, which in your example is i = 5.

The final-expression is executed every time that the loop ends. Then the condition is checked, if it is still TRUE, then the loop will run again with the new value, and so on.

So, your example starts with 5 because the first iteration of the loop is run with the initialization value and the +5 is executed at the end of that first run.

Thanks, I fully understand now! Appreciate it!