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

Math.sign to Determine Number Polarity

Learn how Math.sign returns -1, 0, or 1 to indicate whether a number is negative, zero, or positive.

Math.sign to Determine Number Polarity

You'll learn how Math.sign() gives you a quick, reliable way to check whether a number is positive, negative, or zero.

What is Number Polarity?

Polarity simply means whether a number is positive, negative, or zero. While you could check this with comparison operators (n > 0, n < 0), JavaScript provides Math.sign() as a cleaner, standardized way to determine this in one call.

How Math.sign() Works

Math.sign() takes any number and returns:

  • 1 if the number is positive
  • -1 if the number is negative
  • 0 if the number is exactly zero (or -0 returns -0)
  • NaN if the input isn't a number
console.log(Math.sign(42));      // 1
console.log(Math.sign(-7.5));    // -1
console.log(Math.sign(0));       // 0
console.log(Math.sign(-0));      // -0
console.log(Math.sign("hello")); // NaN

Practical Uses

This becomes especially useful when you need to normalize direction or detect sign changes:

const velocity = -15;
const direction = Math.sign(velocity); // -1 means moving backward

// Conditionally apply logic based on polarity
if (Math.sign(balance) === -1) {
  console.log("Account is overdrawn");
}

// Detect if two numbers have opposite signs
const a = 10;
const b = -20;
const oppositeDirections = Math.sign(a) !== Math.sign(b); // true

Think of Math.sign() like a traffic signal that only shows three colors: green for positive, red for negative, and yellow for zero—instant visual feedback about direction.

Key Takeaway: Math.sign() returns -1, 0, or 1 to instantly tell you a number's polarity, making sign-based logic cleaner and more readable.