Skip to content
Advertisement

Get the absolute value of a number in Javascript

I want to get the absolute value of a number in JavaScript. That is, drop the sign. I know mathematically I can do this by squaring the number then taking the square root, but I also know that this is horribly inefficient.

JavaScript

Is there a way in JavaScript to simply drop the sign of a number that is more efficient than the mathematical approach?

Advertisement

Answer

You mean like getting the absolute value of a number? The Math.abs javascript function is designed exactly for this purpose.

JavaScript

Here are some test cases from the documentation:

JavaScript
Advertisement