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

i++ vs. i+=1

Which is better in a for loop... i++ or i+=1? What is the difference? Which one should I use?

6 Answers

its your choice, What ever you use both will give you the same result but i also use i+=1 ( the reason if you want the loop to jump on two value , just change 1 to 2 and so forth 3 , 4 ,5 .....

Thanks Amin. Great point. I didn't think of incrementing it with 2, 3, etc. GREAT ANSWER!!!

Hi, Mark,

I know I'm 3 months late with this, but the reason you're getting the error is because you're only putting "i+="

When you use the "i+=" you have to have an integer to increment by. Examples: i+=1, i+=2, i+=3, etc. Otherwise, the machine doesn't know how much to increment by each time it passes through the loop.

When you use i++, you're basically just telling the machine to increment i + 1 each time. Just look at it as shorthand.

Hope that helped.

in for loops most people just use i++.

Rashii... Thanks for your response. I've always used i++, since I learned JavaScript back in 2000. But in the JavaScript video... Intro to programming-Objects and Arrays-Arrays, Jim Hoskins used i+=1. Striving to be the BEST programmer I can be, I was wondering which is the best one. Is there a new standard? Best practice? Why didn't he mention the other alternatives?

The i+= throws an error in my for loop for some reason: for(var i =0; i < friends.length; i+=) { console.log(friends[i]); }

but when I use i++ it works fine:

for(var i =0; i < friends.length; i++) { console.log(friends[i]); } console.log(friends[1]);

It throws an error because if you use the i+= you must include a value after the = Ex. for(var i=0; i<friends.length;i+=1){}

Ex. for(var i=0; i<friends.length;i+=3){}

When using i++ the second + indicates the number 1.

So if you add an integer after your += you'll know longer have an error

Thank you Richard.