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:

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

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.