x *= y is a assignment operator which is simply syntactic sugar for x = x * y
There are a lot of similar operator, for example x += y which is more frequent.
You can find the exhaustive list on the revelant page of the MDN documentation
Answer from zoom on Stack Overflowx *= y is a assignment operator which is simply syntactic sugar for x = x * y
There are a lot of similar operator, for example x += y which is more frequent.
You can find the exhaustive list on the revelant page of the MDN documentation
Overview
That is a short function.
x += 1;
x = x + 1; //This is equivalent to the first variable declaration.
Equally this:
result *= base;
is the same as:
result = result * base;
There are several shortcut operators like "+", "-", "*", and the recently added "**". That last one is the exponentiator operator.
2 ** 3 === 2 * 2 * 2; // '===' means strict equivalence (value and type).
result **= base === result = result ** base;
In a loop you write:
for(let i = 0; i < 20; i++) {
/*
* Do something
* That 'i++ is just a shortcut (syntactic sugar) of 'i = i + i'.
* By the way, the 'let' variable means 'i'
* will only be available inside the loop. If you try to
* console.log(i) outside of it, the compiler will return 'undefined'.
*/
}
Videos
It is the addition assignment operator (+=) to add a value to a variable.
Depending of the current type of the defined value on a variable, it will read the current value add/concat another value into it and define on the same variable.
For a string, you concat the current value with another value
let name = "User";
name += "Name"; // name = "UserName";
name += " is ok"; // name = "UserName is ok";
It is the same:
var name = "User";
name = name + "Name"; // name = "UserName";
name = name + " is ok"; // name = "UserName is ok";
For numbers, it will sum the value:
let n = 3;
n += 2; // n = 5
n += 3; // n = 8
In Javascript, we also have the following expressions:
-=- Subtraction assignment;/=- Division assignment;*=- Multiplication assignment;%=- Modulus (Division Remainder) assignment.
text += "The number is " + i;
is equivalent to
text = text + "The number is " + i;
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