Course contentsShow
← JavaScript
Lesson 1596 of 2,72335. Standard Library and Built-insFree lesson

Math.abs for Absolute Values

Use Math.abs to convert negative numbers to positive, essential for distance and magnitude calculations.

Math.abs for Absolute Values

You'll learn how to use Math.abs() to strip away the sign of any number, always getting its positive magnitude.

What Is Math.abs()?

The Math.abs() method returns the absolute value of a number—its distance from zero without regard to direction. Think of it like measuring how far you walked: whether you went 5 blocks north or 5 blocks south, you still traveled 5 blocks total.

How It Works

Math.abs() takes any number and returns its non-negative equivalent:

Math.abs(-42);      // 42
Math.abs(42);       // 42
Math.abs(-3.14);    // 3.14
Math.abs(0);        // 0

Negative inputs become positive. Positive inputs stay positive. Zero stays zero.

Common Use Cases

Distance calculations are the classic example. If you're measuring the difference between two positions, you care about magnitude, not whether one is "before" or "after" the other:

const position1 = 100;
const position2 = 45;
const distance = Math.abs(position1 - position2);  // 55

Temperature differences, error margins, and coordinate differences all benefit from Math.abs():

const temp1 = -5;
const temp2 = 3;
const tempDifference = Math.abs(temp1 - temp2);  // 8 degrees apart

const tolerance = 0.001;
const error = Math.abs(expected - actual);
const isAcceptable = error <= tolerance;

Why It Matters

Absolute value ensures your logic focuses on magnitude rather than sign, making comparisons and calculations more intuitive when direction doesn't matter.

Key Takeaway: Math.abs() converts any number to its positive magnitude, essential for calculating distances, differences, and any scenario where only the size of a value matters, not its sign.