I am still confused with the count operation of the exponentiation operator in javascript

how does the workflow of one operator precedence ie exponentiation I am still confused by the way there work can explain how it works?

1 answer

  • answered 2018-01-11 20:36 6502

    the result of 2 ** 3 is 8 because

    2 * 2 * 2  === 8
    

    i.e. 2 multiplied by itself three times is 8.

    Likewise 2 ** 8 is 256 because

    2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 === 256
    

    The operator is however somewhat "strange" because it is right-associative while all others math operations are left associative:

    x / y / z  ===  (x / y) / z
    x - y - z  ===  (x - y) - z
    
    // but
    
    x ** y ** z  ===  x ** (y ** z)
    

    and also the ** operator plays strangely with unary operators...

    -2**8       // syntax error
    (-2)**8     // ok, value is 256
    -(2 ** 8)   // ok, value is -256
    

    Note also that while the explanation of x ** y as "x multiplied by itself y times" makes sense for non-negative integer values of y, the exponentiation operator is more general and for example x ** 0.5 is the same as Math.sqrt(x).