Math.abs()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Math.abs() は静的メソッドで、数値の絶対値を返します。

試してみましょう

function difference(a, b) {
  return Math.abs(a - b);
}

console.log(difference(3, 5));
// Expected output: 2

console.log(difference(5, 3));
// Expected output: 2

console.log(difference(1.23456, 7.89012));
// Expected output: 6.6555599999999995

構文

js
Math.abs(x)

引数

x

数値です。

返値

x の絶対値です。x が負または -0 の場合は、その反対の数である -x (非負の値)を返します。それ以外の場合、x 自体を返します。したがって、返値は常に正の値または 0 となります。

解説

abs()Math オブジェクトの静的メソッドなので、 Math オブジェクトを生成してメソッドとして使用するのではなく、常に Math.abs() として使用するようにしてください (Math はコンストラクターではありません)。

Math.abs() の使用

js
Math.abs(-Infinity); // 無限大
Math.abs(-1); // 1
Math.abs(-0); // 0
Math.abs(0); // 0
Math.abs(1); // 1
Math.abs(Infinity); // 無限大

Math.abs() の動作

空のオブジェクト、複数のメンバーを持つ配列、数値でない文字列、 undefined、 空の変数を渡すと、 NaN を返します。 null を渡すと空文字列を返し、空の配列は 0 を返します。

js
Math.abs("-1"); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(""); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1, 2]); // NaN
Math.abs({}); // NaN
Math.abs("string"); // NaN
Math.abs(); // NaN

仕様書

Specification
ECMAScript® 2025 Language Specification
# sec-math.abs

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
abs

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報