JavaScript: Calculating Absolute Value with Math.abs

Posted on January 04, 2021


You can find the absolute value of a number in JavaScript by using the Math.abs() method. The absolute value of a number means how far a number is from zero.

Math.abs() only takes one number type parameter and return the absolute value of that number:

Math.abs(-5);
Math.abs(5);

// both returns 5

Both the negative number -5 and the positive number 5 is 5 numbers away from zero (so both returns 5)

When you pass more than one parameter, JavaScript will ignore the rest and operate only on the first:

Math.abs(-3, 5);
Math.abs(-3, "Hello");

// returns 3

When you pass non-number data type, the method will return NaN as value:

Math.abs("String");

// returns NaN

More on JavaScript Math operation:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more