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

Andrew Shumway
Andrew Shumway
3,848 Points

++ vs +=

From what I understand about using ++ and += they essentially are supposed to do the same thing however when I used ++ in the following code, it return an error of "unexpected number" for what followed the ++. Changing it to += solved the issue. Why is that?

***this code did not work.

var text = "test loop";
var loopNum = 0;
var loop = function(){
    while(loopNum < 3){
        loopNum++1;
        console.log(text);
    }
};

loop();

***This code did work.

var text = "test loop";
var loopNum = 0;
var loop = function(){
    while(loopNum < 3){
        loopNum+=1;
        console.log(text);
    }
};

loop();

2 Answers

Michael Hulet
Michael Hulet
47,911 Points

The difference between ++ and += is that the ++ operator doesn't take a number on the left, and only adds 1 to the number on the left, but the += operator takes a number on each side, and adds the number on the right to the number on the left. For example:

var number = 0;

//These statements are equivalent
number++;
number += 1;

//This statement adds 2 to number
number += 2;

//This statement is invalid and illegal
number ++ 2;
Erik Nuber
Erik Nuber
20,629 Points

The ++ operator just adds one to a given variable so i++ would increase i by one

+= can be used to add to an existing variable a specific amount or just about anything

ex:

lastName = Nuber;
fullName = Erik;
fullName += " ";
fullName += lastName;

This woudl return Erik Nuber with the space between beacause I added it in.

This would add lastName to the fullName. This can be cleaned up and put on one line but using it this way to make a point.

In your first code try just removing ++1 and just use ++