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

Why result is different ?!!

let i;
let text;

i = 0;
do {
  text += i + ' ';
  i += 1;
  } while(i <= 4)

in this case the output will be 0 1 2 3 4.

but why if i write like this :

i = 0;
do {
  i += 1;
  text += i + ' ';
  } while(i <= 4)

the out put will be '1 2 3 4 5 ' !! why in 'for' loop the i +=1 come first !

1 Answer

Steven Parker
Steven Parker
231,153 Points

It sounds like you nearly answered your own question. In the first example, the number is added to "text" before it is incremented, but in the second example it is added after.

So the first series begins with 0, and the second one begins with 1 (0 + 1).

But both of these are "do...while" loops. A "for" loop works differently in several ways, including performing the test first instead of last.

Thank you so much it's clear now !