How does += (plus equal) work?
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 = ?
Solution 1:
1 += 2
is a syntax error (left-side must be a variable).
x += y
is shorthand for x = x + y
.
Solution 2:
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
Solution 3:
That is just a short form for:
sum = sum + value;
Solution 4:
+=
in JavaScript (as well as in many other languages) adds the right hand side to the variable on the left hand side, storing the result in that variable. Your example of 1 +=2
therefore does not make sense. Here is an example:
var x = 5;
x += 4; // x now equals 9, same as writing x = x + 4;
x -= 3; // x now equals 6, same as writing x = x - 3;
x *= 2; // x now equals 12, same as writing x = x * 2;
x /= 3; // x now equals 4, same as writing x = x / 3;
In your specific example the loop is summing the numbers in the array data
.