5

For example, in the while loop:

while (i < 10) {
    text += "The number is " + i;
    i++;
}

What does it do? Thanks.

HappyHands31
  • 4,001
  • 17
  • 59
  • 109
  • 1
    [+=](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment) – hindmost Oct 05 '15 at 20:57

2 Answers2

20

It is the addition assignment operator (+=) to add a value to a variable.

Depending of the current type of the defined value on a variable, it will read the current value add/concat another value into it and define on the same variable.

For a string, you concat the current value with another value

let name = "User";

name += "Name"; // name = "UserName";
name += " is ok"; // name = "UserName is ok";

It is the same:

var name = "User";

name = name + "Name"; // name = "UserName";
name = name + " is ok"; // name = "UserName is ok";

For numbers, it will sum the value:

let n = 3;

n += 2; // n = 5
n += 3; // n = 8

In Javascript, we also have the following expressions:

  • -= - Subtraction assignment;

  • /= - Division assignment;

  • *= - Multiplication assignment;

  • %= - Modulus (Division Remainder) assignment.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
6
text += "The number is " + i;

is equivalent to

text = text + "The number is " + i;
slomek
  • 4,873
  • 3
  • 17
  • 16