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

Damian Loyola
Damian Loyola
9,315 Points

is this loop syntax valid in JS??

for(var i=0; i <10; i++){
}

i have seen in the javascript videos that the teacher use i+=1 , is i++ valid too? or im just confusing with other programming language?

4 Answers

Steven Parker
Steven Parker
231,275 Points

Yes, JavaScript implements this operation.

In fact, JavaScript implements a unary increment prefix ("++i") and a unary increment postfix ("i++") along with the addition assignment ("i+=1") operator. In a stand-alone context like this they all do the same thing as "i = i + 1".

But be aware that the postfix operator is not quite the same as the others. If you do something that makes use of the value of the operation, the postfix returns the value before the increment:

let i = 3;
console.log(i++); 
// the value of "i" will be 4 here, but the log will show 3

Hey Damian,

This is valid JavaScript.

If you log i, you'll see 0 through 9.

Thomas Nilsen
Thomas Nilsen
14,957 Points
var i = 0

//These two are exactly the same
i++;
i += 1
Damian Loyola
Damian Loyola
9,315 Points

thank you all, very clear answers :D