Math.sign()

ES6+

Returns the sign of a number, indicating whether the number is positive, negative, or zero.

Syntax

Math.sign(x)

Parameters

x number

A number

Return Value

number

1, -1, or 0 indicating the sign of the number

Examples

JavaScript
console.log(Math.sign(5));
console.log(Math.sign(-5));
console.log(Math.sign(0));
Output:
// 1 -1 0

📌 When to Use

Use Math.sign() for direction detection, movement in games, sorting comparisons, or extracting just the sign component from a number.

⚠️ Common Mistakes

Expecting Math.sign() to return the actual number - it only returns -1, 0, or 1.

Forgetting that Math.sign() returns NaN for non-numeric inputs.

✅ Best Practices

Use Math.sign() for comparator functions: (a, b) => Math.sign(a - b) for numeric sorting.

Combine with Math.abs() to reconstruct numbers: sign * Math.abs(number).

⚡ Performance Notes

Math.sign() is highly optimized. While (x > 0) - (x < 0) is technically equivalent, Math.sign() is clearer and equally fast.

🌍 Real World Example

Game Character Movement Direction

Determine character facing direction and normalize movement velocity in a 2D game.

function updateCharacterMovement(velocityX, velocityY) {
  const direction = {
    x: Math.sign(velocityX),
    y: Math.sign(velocityY)
  };

  const facing = direction.x === 0
    ? (direction.y > 0 ? 'down' : 'up')
    : (direction.x > 0 ? 'right' : 'left');

  return {
    direction,
    facing,
    isMoving: direction.x !== 0 || direction.y !== 0
  };
}

console.log(updateCharacterMovement(5.5, 0));
// { direction: { x: 1, y: 0 }, facing: 'right', isMoving: true }

console.log(updateCharacterMovement(-2.3, -4.1));
// { direction: { x: -1, y: -1 }, facing: 'left', isMoving: true }

Related Methods