The plus equal operator +=
in JavaScript is a shorthand operator that allows you to add the value from the right operand to the left operand.
For example, you can add 3
to the num
like this:
let num = 7;
num += 3;
console.log(num); // 10
This +=
operator is also known as the addition assignment operator. The use is equal to the regular addition operator.
num += 3;
// same as
num = num + 3;
Just like when using the addition operator, a type coercion is executed each time you use the operator. The priorities of the coercion are as follows:
- Convert to string when there is a string value
- Objects and arrays are converted to string
- When there a is number value but no string, convert to number
- Boolean will be converted to
number
types when there is no string
The string
type is always number one priority, with number
type coming second.
Here are several examples of addition assignment in action:
let str = "hello";
let arr = [1, 2];
let num = 9;
let bool = true;
str += 2; // string "hello2"
num += 2; // 11
arr += 3; // string "1,23"
bool += true; // number 2