JavaScript: Calculating Absolute Value with Math.abs

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:


// 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:


// returns NaN

Get 100 JavaScript Snippets Book for FREE 🔥

100 JavaScript snippets that you can use in various scenarios

Save 1000+ hours of research and 10x your productivity