logo
post image

How to Check Number is Positive or Negative in Javascript (ES6 Way)

Use-Cases of this Tutorial

  • Know how to check a number is positive or negative without using conditional statements or operators.
  • Know about the Math.sign() method.

The Math.sign() is a new method introduced in ES6 that can be used to find whether a number is positive or negative or a zero.

Finding whether a number is positive or negative is a very commonly occurring task in programming. It is mostly done using conditional statements (if-else) or operators.

However Math.sign() is a new method added to Javascript that tells whether a given number is positive or negative or zero.

Math.sign() accepts a single number as its parameter. The return value can be used to determine the sign of the passed number.

  • Return value of 1 represents a positive number.
  • Return value of -1 represents a negative number.
  • Return value of 0 reprsents a positive zero.
  • Return value of -0 represents a negative zero.
  • Return value of NaN means that the parameter passed is not a numeric data type.
// 1
Math.sign(10);

// -1
Math.sign(-12);

// 0
Math.sign(0);

// -0
Math.sign(-0);