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

Is i++ the same as +=1 in javascript ?

I am looking at loops, and I am wondering if these two codes are the same, but the second option uis just a faster way to type? Thanks

for (i = 0; i < 5; i += 1) { text += "The number is " + i ; }

VS

for (i = 0; i < 5; i++) { text += "The number is " + i ; }

i += 1 is the shorthand for:   var  i = i + 1;

i++ is another shorthand to increment the variable by JUST 1

i-- will decrement the variable by 1

so, the advantage of using i += 1 - is that you have more flexibility with the way the variable increments 

example: i += 5, i += 10 etc.

Hope this helped

1 Answer

Actually in this case yes and in a for statement I recommend you use i++ unless you need to step by a higher number. Say if you needed to loop through a list by 2's then you can use +=2.

You might always want to experiment with ++i which.