For example, in the while loop:
while (i < 10) {
text += "The number is " + i;
i++;
}
What does it do? Thanks.
For example, in the while loop:
while (i < 10) {
text += "The number is " + i;
i++;
}
What does it do? Thanks.
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.
text += "The number is " + i;
is equivalent to
text = text + "The number is " + i;