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

jason chan
jason chan
31,009 Points

What's the difference between ++ vs += 1 for javascript counter?

What's the difference between ++ vs +=1 for javascript?

Why didn't he teach ++ seems like easier notation and you don't have to type three characters?

2 Answers

rigoberto contreras
rigoberto contreras
9,035 Points

++ increases the integer by one and += increases the integer by the number of your choice.

jason chan
jason chan
31,009 Points

thanks rigoberto you rock! yeah kind of figured that out.

++ is only for increase by number and += anything.

You should avoid using ++ (and --). Not only does += (or -=, *=, etc) give you more power over your interval, it will also eliminate confusing errors that may come up down the road from using a ++/-- operator, especially since you can put var++ or ++var and in some cases they will work the same and in others, they won't.

For example:

var counter = 0;
var myArray = [];
//You would think that this would increase the counter variable and then
//assign the value "foo" to that index
//But instead it uses the present value of counter as the index and then increases counter
myArray[counter++] = "foo";
console.log(myArray[0]); //Returns foo at index 0
console.log(counter); //Returns 1

And then this case:

var counter = 0;
var myArray = [];
//Using ++counter will instead increase counter first and then
//use the value it just got as the index
//in this case 1
myArray[++counter] = "foo";
console.log(myArray[1]); //Returns foo at index 1, 0 is undefined
console.log(counter); //Returns 1
M Baker
seal-mask
.a{fill-rule:evenodd;}techdegree
M Baker
Full Stack JavaScript Techdegree Student 5,983 Points

Marcus: I would argue that it is doing exactly what it's supposed to do in your examples and your examples are highlighting why we do need to have / use the increment operator (++) in our code, when we need it and when we understand it. I use it all the time.