-3

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

  • 1
    a*=b is shorthand for a=a*b – chiliNUT Jul 23 '16 at 20:52
  • 1
    it means you need to read the [JavaScript documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Multiplication_assignment) before asking others to read it for you! –  Jul 23 '16 at 20:56
  • Possible duplicate of [Simple substitute of assignment operators of logical ones in JavaScript?](http://stackoverflow.com/questions/20752183/simple-substitute-of-assignment-operators-of-logical-ones-in-javascript) which mentions not just this one but all of them! –  Jul 23 '16 at 20:57
  • @JarrodRoberson it might mention it, but that's a different question. – David Sherret Jul 23 '16 at 21:00
  • 1
    Being a beginner, you should learn how to research before asking. And you will be like the latter once you realise that the information people are looking for is right in from of them. – Pogrindis Jul 23 '16 at 21:19
  • 1
    It's not a mentor site.. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators Google's first result. – Pogrindis Jul 23 '16 at 21:21
  • duplicates are based on the information in the **answer** and **not** the context of the *question*. –  Jul 23 '16 at 22:57

2 Answers2

2

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

zoom
  • 1,686
  • 2
  • 16
  • 27
-1

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'.
  */
}
Community
  • 1
  • 1
Pablo Ivan
  • 280
  • 2
  • 15