How to get the absolute value of a number in JavaScript

Getting the absolute value of numbers is essential for distance calculations, difference measurements, validation ranges, and implementing features like progress indicators or mathematical computations in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented absolute value calculations extensively in components like progress bars, distance meters, and validation systems where the magnitude of a value matters more than its sign. From my extensive expertise, the most direct and mathematically correct approach is using the built-in Math.abs() function. This method is simple, efficient, and specifically designed for obtaining the non-negative magnitude of numbers.

Use Math.abs() to get the absolute value of a number.

const negativeNumber = -42
const absoluteValue = Math.abs(negativeNumber)
// Result: 42

const positiveNumber = 15
const stillPositive = Math.abs(positiveNumber)
// Result: 15

The Math.abs() function returns the absolute value of a number, which is its magnitude without regard to sign. For negative numbers, it removes the minus sign and returns the positive equivalent. For positive numbers and zero, it returns the number unchanged. In these examples, Math.abs(-42) returns 42, and Math.abs(15) returns 15. The function handles integers, decimals, and special values: Math.abs(-3.14) returns 3.14, and Math.abs(0) returns 0.

Best Practice Note:

This is the same approach we use in CoreUI components for calculating distances, measuring differences, and implementing range validations across our component library. The Math.abs() function handles edge cases properly: Math.abs(-Infinity) returns Infinity, and Math.abs(NaN) returns NaN. For very large numbers, consider potential precision limitations. This method is universally supported and provides the most reliable way to obtain absolute values in JavaScript.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What is the difference between typeof and instanceof in JavaScript
What is the difference between typeof and instanceof in JavaScript

How to sleep in Javascript
How to sleep in Javascript

How to Get Unique Values from a JavaScript Array
How to Get Unique Values from a JavaScript Array

How to replace all occurrences of a string in JavaScript?
How to replace all occurrences of a string in JavaScript?

Answers by CoreUI Core Team