Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. Math
  6. abs()

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.

TheMath.abs() static method returns the absolute value of a number.

Try it

function difference(a, b) {  return Math.abs(a - b);}console.log(difference(3, 5));// Expected output: 2console.log(difference(5, 3));// Expected output: 2console.log(difference(1.23456, 7.89012));// Expected output: 6.6555599999999995

Syntax

js
Math.abs(x)

Parameters

x

A number.

Return value

The absolute value ofx. Ifx is negative or-0, returns its opposite number-x (which is non-negative). Otherwise, returnsx itself. The result is therefore always a positive number or0.

Description

Becauseabs() is a static method ofMath, you always use it asMath.abs(), rather than as a method of aMath object you created (Math is not a constructor).

Examples

Using Math.abs()

js
Math.abs(-Infinity); // InfinityMath.abs(-1); // 1Math.abs(-0); // 0Math.abs(0); // 0Math.abs(1); // 1Math.abs(Infinity); // Infinity

Coercion of parameter

Math.abs()coerces its parameter to a number. Non-coercible values will becomeNaN, makingMath.abs() also returnNaN.

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

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp