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 trialDamian Loyola
9,315 Pointsis 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
231,275 PointsYes, 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
jacobproffer
24,604 PointsHey Damian,
This is valid JavaScript.
If you log i, you'll see 0 through 9.
Thomas Nilsen
14,957 Pointsvar i = 0
//These two are exactly the same
i++;
i += 1
Damian Loyola
9,315 Pointsthank you all, very clear answers :D