How to use the JavaScript += operator?

In this tutorial, we look at how to use the JavaScript += operator. We explain its use-case and break down the code to allow further learning.

JavaScript +=

Table of Contents - JavaScript +=

  • What does += mean in JavaScript?
  • Syntax, Code & Explanation
  • Closing thoughts - JavaScript +=
  • Other Related Concepts

What does += mean in JavaScript?

The JavaScript += operator takes the values from the right of the operator and adds it to the variable on the left. This is a very concise method to add two values and assign the result to a variable hence it is called the addition assignment operator.

This operator is not only used to add numerical values but can also be used to concatenate strings together. Essentially it replaces the variable = a + b syntax with a += b.

Syntax, Code & Explanation:

The syntax of the assignment operator is quite straightforward and does not require any prerequisites.

x += y
In case you are still confused, I shall break it down even further. This method is just a shorter way of writing the following code.

x = x + y
Here we are again taking the value on the right (y) and adding & assigning it to the value on the left (x). The assignment operator does the same in a more concise method.

Code using JavaScript +=:

//Code using JavaScript +=
//On int values
let x = 2;
let y = 5;
console.log(x += y); 
//On strings
let a = 'Hello'
let b = ' World'
console.log(a += b)

The Output of the above code snippet is as follows.

> 7
> "Hello World"
As you can see, the values of ‘y’ & ‘b’ have been added to the ‘x’ & ‘a’ respectively.

Closing thoughts - JavaScript +=:

Using the JavaScript += operator would help increase code readability, and such minor changes would help while working with a group of senior developers.

Once you have familiarized yourself with the addition assignment operator (+=) I would recommend practicing the other assignment operators. There are seven in total ( =, +=, -=, *=, /=, %=, **= ), and mastering them all would help you go a long way.