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:
Which is equivalent to:
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”:
Add “15” in “val1” utilizing the += operator and print the resultant value on the console:
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:
Now, add a string “hint” in a variable “str1” using addition assignment operator:
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”:
Now, add a number “22” as a string in the variable “val1”. It will concatenate with the value of val1:
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.