Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does += (plus equal) work?

Tags:

javascript

I'm a bit confused with the += sign. How does it work?

  1. 1 += 2 // equals ?

  2. and this

    var data = [1,2,3,4,5]; var sum = 0; data.forEach(function(value) {     sum += value;  }); sum = ? 
like image 678
muudless Avatar asked Jul 26 '11 06:07

muudless


People also ask

How does += operator work?

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.

Can you use += in JavaScript?

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.

What does -= mean in JavaScript?

The subtraction assignment operator ( -= ) subtracts the value of the right operand from a variable and assigns the result to the variable.

How do you sum in JavaScript?

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.


2 Answers

1 += 2 is a syntax error (left-side must be a variable).

x += y is shorthand for x = x + y.

like image 97
lawnsea Avatar answered Oct 08 '22 13:10

lawnsea


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 
like image 35
Paul Avatar answered Oct 08 '22 14:10

Paul