LoginSignup
42
38

More than 5 years have passed since last update.

べき乗をするならMath.pow()よりもExponentiation Operatorが手軽(ES2016新機能)

Last updated at Posted at 2016-06-17

2016/06/17、JavaScriptの仕様「ECMAScript」の最新バージョンECMAScript 2016(※)がリリースされました。ES2016で追加された機能は2つです。

  • Exponentiation(**) Operator
  • Array.prototype.includes()メソッド

本エントリーでは、Exponentiation(**) Operatorについて解説します。Array.prototype.includes()メソッドについてはこちらの記事で解説しています。
配列内の要素の存在確認にはArray.includes()メソッドが便利

※ 言語仕様書:「ECMAScript® 2016 Language Specification

Exponentiation Operatorはべき乗計算のための新しいオペレータ

これまでJavaScriptでべき乗計算(2の3乗や、4の8乗などの計算のこと)は、Math.pow()を使って行っていました。

// 2の3乗算
Math.pow(2, 3);
// 4の8乗算
Math.pow(4, 8);

▲ Google Chromeでの計算結果

Exponentiation Operatorは、**を記述することで、このべき乗計算をシンプルに書けるようになります。ちなみに「Exponentiation」が「べき乗」という意味です。

では、先ほどの計算を書き換えてみましょう。

// 2の3乗算
2 ** 3;
// 4の8乗算
4 ** 8;

▲ Google Chromeでの計算結果

Math.pow()を使うよりもシンプルな記述で可能なことがわかります。

また、次のような記述も可能です。

// 変数aに2を代入する。
let a = 2;
// aの3乗を得る。
a **= 3;

▲ Google Chromeでの計算結果

便利ですね。

対応ブラウザは?

2018/02/06時点では、IE 11を除く全主要ブラウザで対応しています。

参考:ECMAScript Next compatibility table

IE 11でも対応する必要がある場合は、TypeScriptやBabelを経由するのがおすすめです。

42
38
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
42
38