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

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,842 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 ++