JavaScript += operator explained

Posted on Apr 19, 2021

Here's how the plus equal (+=) operator works in JavaScript


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:

  1. Convert to string when there is a string value
  2. Objects and arrays are converted to string
  3. When there a is number value but no string, convert to number
  4. 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

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.