Compound Assignment With Augmented Addition has me confused

Hey there. Its not that i need help with the challenge, its pretty short and straighforward. Its just that i dont understand the difference between:

var myVar = 1;
myVar += 5;

and

var myVar = 1;
myVar + 5;

Both do the same in my eyes, so what am i missing?

Thanks!

the first example is ok the second is bad because it is assignment.

should be
myVar=myVar + 5;

the advantage with the first example is that you write less code.

The above is just a shortcut way to write

myVar = myVar + 5;

That’s it. The shortcut just allows you to avoid some repetition in typing.

2 Likes

I get that. But in the challenge explanation, the code is:

var myVar = 1;
myVar += 5;

Why not just do:

var myVar = 1;
myVar + 5;

without the =?

I mean, why do we need to say that my variable is equal to its value plus another value (x = x + 1) when just adding that other value to my variable (x + 1) will suffice?

Just having the following on a line by it’s own:

myVar + 5;

doesn’t really do anything. It creates the value 6 in this case, but it doesn’t save it anywhere. So there is no reason you would do that. If you want the value in myVar to increase by 5 then you need to add 5 to it AND save it back into myVar.

1 Like

+= is used to update the value of the variable. Sometimes after you create a variable you will want to update the value. This syntax lets you do it more compactly.

1 Like

Yes, i figured it out as soon as i wrote that last reply while i was opening chrome console saying ‘Wait a minute, X + 1 isnt gonna update X value!’. Im a moron!

Thanks @BobSmith and @bbsmooth !

1 Like

Not a moron. We all have our hiccups when learning this stuff. The important thing is that now you have thought it through and understand the concept. That’s how we learn. Mistakes aren’t always bad.

2 Likes

Thanks! It takes me forever sometimes but i think thats works the best for me. I could have just completed the challenge and sprint through the JS course but in a month i wouldnt remember a thing.

I said im a moron because ive been working as a trainee front end dev for the last 3 months and ive done far more complex things than this.