The JavaScript += addition assignment operator will take the value on the right side of the operator and add it to the value of the variable on the left side of the addition operator.
someVaraible += 3;
The above code would be the equivalent of:
someVaraible = someVaraible + 3;
Let’s see a simple example of this below.
In the example below, we will have an array of numbers that we will want to get the total value of. We will do this by using a JavaScript function that will use a for loop and the += assignment operator to add all the numbers in the array. Here is the JavaScript code below:
var numbersArray = [4,3,5,8,14,67,56,23];
function addArray(theArray){
var arrayTotal = 0;
for (var i = 0; i < theArray.length; i++) {
arrayTotal += theArray[i];
}
return arrayTotal;
}
var addUpArray = addArray(numbersArray);
The variable addUpArray above would have value 180, which is what you get if you add up all the numbers in the array numbersArray.
Interactive Example of the JavaScript += Addition Assignment Operator
Below we will provide code to let the user input as many numbers as they want separated by a comma(,).
Here is the simple HTML set up:
Type as many numbers as you want separated by a comma.
If the numbers are not separated by a comma only, this example will not work.
We will then create an array of numbers from this input and add up all the numbers with the help of the JavaScript += operator, just like we did in the function we created above.
To create an array from the string of numbers the user provides, we will use the split() method along with the Array map() method. We will add this code to our addArray function.
We will update the results below using the textContent property..
function addArray(){
//Get the user input
var userInput = document.getElementById("userArr").value;
//Convert user input to an array of numbers
var numbersArray = userInput.split(',').map(Number);
//Add all of the numbers together
var arrayTotal = 0;
for (var i = 0; i < theArray.length; i++) {
arrayTotal += theArray[i];
}
//Display the sum of the numbers the user has entered
document.getElementById("results").textContent = "The sum of the numbers is: " + arrayTotal;
}
The final code and output for this example is below:
Code Output:
Type as many numbers as you want separated by a comma.
If the numbers are not separated by a comma only, this example will not work.
Full Code:
Type as many numbers as you want separated by a comma.
If the numbers are not separated by a comma only, this example will not work.
<script>
function addArray(){
var userInput = document.getElementById("userArr").value;
var numbersArray = userInput.split(',').map(Number);
var arrayTotal = 0;
for (var i = 0; i < numbersArray.length; i++) {
arrayTotal += numbersArray[i];
}
document.getElementById("results").textContent = "The sum of the numbers is: " + arrayTotal;
}
</script>
Hopefully this article has helped you to understand how to use the JavaScript += addition assignment operator