JavaScript

Addition Assignment or += Operator in JavaScript

The addition assignment += operator in JavaScript adds the values from the operator’s right to the variable on the left. Adding two numbers and assigning the output to a variable may be done simply using this addition assignment += operator. It can be utilized to concatenate the strings and add numerical numbers.

This tutorial will demonstrate the addition assignment operator += in JavaScript.

What is Addition Assignment or += Operator in JavaScript?

The addition assignment += operator is the short form for adding or concatenating the two variables and then assigning the resultant value to another variable. As compared to the standard variable = X + Y, the addition assignment += operator is more feasible.

Syntax
The syntax of the addition assignment operator is:

a += b

Which is equivalent to:

a = a + b

Let’s try some examples of using the addition assignment += operator.

Example 1: Add Number in Variable using Addition Assignment += Operator
First, create a variable “val1” by assigning the value “11”:

var val1 = 11;

Add “15” in “val1” utilizing the += operator and print the resultant value on the console:

console.log(val1 += 15);

The output displays “26” after adding “15” into “11”:

Example 2: Add Two Strings using Addition Assignment += Operator
Create a variable “str1” and store a string “Linux” in it:

var str1 = "Linux";

Now, add a string “hint” in a variable “str1” using addition assignment operator:

console.log(str1 += "hint");

The output indicates that the string “hint” is successfully concatenated with the string “Linux” that is stored in a variable “str1”:

Example 3: Add a String in a Number using Addition Assignment += Operator
Create a variable “val1” and assign a value “2”:

var val1 = 2;

Now, add a number “22” as a string in the variable “val1”. It will concatenate with the value of val1:

console.log(val1 += '22');

Output

We have covered the basics of the addition assignment += operator in JavaScript.

Conclusion

The addition assignment operator (+=) adds to a variable’s value. It works just like writing x = x + y. So basically, this addition assignment operator performs two actions simultaneously. These actions add the values of the two operands and then store the result in the left operand. Another interesting fact about the addition assignment operator is that the user can also use it to concatenate two string values. This tutorial demonstrated the JavaScript addition assignment operator += and its uses.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.