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 Introduction to Programming Objects and Arrays Arrays

What is the difference between i+=1 and i++

I found out that i++ is an increment of i by whereas in this chapter, the teacher uses i+=1 instead. May I know what is the difference between two? Thank you very much.

4 Answers

Laura Cressman
Laura Cressman
12,548 Points

There is no difference, both do the same thing.

The i++ is shorthand for i += 1.

You can use other numbers for +=, like "i += 2" if you wanted to print only even numbers, for example, but i++ only increments by one. We also have i--, which is the same as i -= 1.

Does that make sense?

Russell Beye
Russell Beye
3,367 Points

Let's explore this side-by-side:

i++: Here, the value of i is returned first, then it is incremented. In a common example, if you set i = 1, and x = i++, you should find that x = 1. This is called post increment.

++i: In this case, i is first incremented and then returned. Again, i = 1, x = ++i, you'll find x = 2. This is called pre increment.

In an overwhelming amount of cases, this won't be a problem as it won't affect your loops. It's nice to know what is out there though. I would prefer to use i++ because it maintains the form of a proper expression; the target operand is on the left side of the expression.

You can learn more: http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i

Thanks Laura for the answer!

Russell Beye
Russell Beye
3,367 Points

Don't forget that we also have ++i, which can have different side effects than i++. ;)

Hi Russell, can you tell me more about ++1? Like what does this formula returns?