Jen Billingston Jen Billingston - 4 months ago 12
Javascript Question

What does this *= symbol mean in Javascript? THANK YOU to the people who decide to be kind about this.

I am currently reading Eloquent Javascript, and this keeps coming up:

*=


in context:

function power(base, exponent) {
if (exponent == undefined)
exponent = 2;
var result = 1;
for (var count = 0; count < exponent; count++)
result *= base;
return result;
}

console.log(power(4));
// → 16
console.log(power(4, 3));
// → 64


I'm a beginner so please explain as if I were a 5 year old (not too far off). Thank you

Answer

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'.
  */
}