-5

The operator += is one that I have seen a lot in JavaScript and I have absolutely no idea what it does. Can someone simply define what it is and how I would use it in JavaScript? I found this example and I don't understand what is happening.

var message = "";
if (document.getElementById("x") == "") {
    message += "You must enter your last name."
}
Gabriele Petrioli
  • 173,972
  • 30
  • 239
  • 291
Jack Davis
  • 61
  • 2
  • 2
  • 8

3 Answers3

3

It is an assignment shortcut operator

x += y means x = x + y

See the Shorthand Assignment operator table.


In javascript the + operator works on strings as well by concatenating them.. So in your case it will add to the message variable the string on the right side..

user2864740
  • 54,112
  • 10
  • 112
  • 187
Gabriele Petrioli
  • 173,972
  • 30
  • 239
  • 291
2

It does the same thing as it does in C and Java and many other languages:

x += y;

is a shorthand for

x = x + y;
Paul
  • 130,653
  • 24
  • 259
  • 248
0

In that case it means message = message + "You must enter your last name.". There might be some edge cases when variables are of different types and are automatically transformed to other types (which might produce unexpected results), but this does not seem to be the case.

Damian Schenkelman
  • 3,439
  • 1
  • 13
  • 19