Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
–
–
–
–
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;
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
+=
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
.
+=
operator is used to concatenate strings or add numbers.
It will increment your sum variable with the amount next to it.
var sum = 0;
var valueAdded = 5;
sum += valueAdded;
sum = 5
Assignment operators syntax is: variable = expression;
For this reason 1 += 2
-> 1 = 1 + 2
is not a valid syntax as the left operand isn't a variable. The error in this case is ReferenceError: invalid assignment left-hand side
.
x += y
is the short form for x = x + y
, where x
is the variable and x + y
the expression.
The result of the sum is 15.
sum = 0;
sum = sum + 1; // 1
sum = sum + 2; // 3
sum = sum + 3; // 6
sum = sum + 4; // 10
sum = sum + 5; // 15
Other assignment operator shortcuts works the same way (relatively to the standard operations they refer to).
–
you are going to add 1+2
.
But this will give you a syntax error.
Assume if a variable is int type int a=1
;
a+=2
; means a=1+2
; and increase the value of a from 1 to 3.
1 += 2
won't throw an error but you still shouldn't do it. In this statement you are basically saying "set 1 equal to 1 + 2" but 1 is a constant number and not a variable of type :number
or :string
so it probably wouldn't do anything. Saying
var myVariable = 1
myVariable += 2
console.log(myVariable)
would log 3
to the console, as x += y
is just short for x = x + y
var data = [1,2,3,4,5]
var sum
data.forEach(function(value){
sum += value
would make sum
= 15 because:
sum += 1 //sum = 1
sum += 2 //sum = 3
sum += 3 //sum = 6
sum += 4 //sum = 10
sum += 5 //sum = 15