I'm a bit confused with the += sign. How does it work?
1 += 2
// equals ?
and this
var data = [1,2,3,4,5]; var sum = 0; data.forEach(function(value) { sum += value; }); sum = ?
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.
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.
The subtraction assignment operator ( -= ) subtracts the value of the right operand from a variable and assigns the result to the variable.
const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.
1 += 2
is a syntax error (left-side must be a variable).
x += y
is shorthand for x = x + y
.
1) 1 += 2 // equals ?
That is syntactically invalid. The left side must be a variable. For example.
var mynum = 1; mynum += 2; // now mynum is 3.
mynum += 2;
is just a short form for mynum = mynum + 2;
2)
var data = [1,2,3,4,5]; var sum = 0; data.forEach(function(value) { sum += value; });
Sum is now 15. Unrolling the forEach we have:
var sum = 0; sum += 1; // sum is 1 sum += 2; // sum is 3 sum += 3; // sum is 6 sum += 4; // sum is 10 sum += 5; // sum is 15
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With