4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ES2016(ES7)で実装されたべき乗演算子(Exponentiation Operator)の挙動について

Posted at

ES2016で実装された ** だが、
単項マイナス演算子が左辺にある場合、SyntaxErrorとなる。

2 ** 2 // 4
2 ** -2 // 0.25
-2 ** 2 // Uncaught SyntaxError: Unexpected token **

ESにおける演算子の優先順位が単項マイナス→べき乗で、
他の多くの言語(べき乗→単項マイナス)で得られる結果を期待すると混乱が起こるため、
この実装は理にかなっているように思う。

(-2) ** 2 // 4 単項マイナス→べき乗の順だとこうなるが…
-(2 ** 2) // -4 多くの言語ではこちらの実装になっている

演算子の優先順位 - JavaScript | MDN
Exponentiation operator precedence

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?