Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,083 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