Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is Addition Assignment Operator (+=) in JavaScript?
The Addition Assignment Operator (+=) adds the right operand to the left operand and assigns the result back to the left operand. It's a shorthand way of writing a = a + b.
Syntax
variable += value; // Equivalent to: variable = variable + value;
Example with Numbers
Here's how the addition assignment operator works with numeric values:
<html>
<body>
<script>
var a = 33;
var b = 10;
document.write("Initial value of a: " + a + "<br>");
document.write("Value of b: " + b + "<br>");
a += b; // Same as: a = a + b
document.write("After a += b, value of a: " + a);
</script>
</body>
</html>
Initial value of a: 33 Value of b: 10 After a += b, value of a: 43
Example with Strings
The += operator also works with strings for concatenation:
<html>
<body>
<script>
var greeting = "Hello";
var name = " World";
document.write("Initial greeting: " + greeting + "<br>");
greeting += name; // String concatenation
document.write("After concatenation: " + greeting);
</script>
</body>
</html>
Initial greeting: Hello After concatenation: Hello World
Common Use Cases
The addition assignment operator is commonly used in:
- Counter increments:
count += 1 - Sum calculations:
total += price - String building:
message += newText
Conclusion
The += operator provides a concise way to add and assign values in one operation. It works with both numbers (addition) and strings (concatenation), making code more readable and efficient.
Advertisements
