Categories
JavaScript Answers

How to check if a number is negative with JavaScript?

Spread the love

Sometimes, we want to check if a number is negative with JavaScript.

In this article, we’ll look at how to check if a number is negative with JavaScript.

How to check if a number is negative with JavaScript?

To check if a number is negative with JavaScript, we use the Math.sign method.

For instance, we write

const number = 1;

if (Math.sign(number) === 1) {
  console.log("I'm positive");
} else if (Math.sign(number) === -1) {
  console.log("I'm negative");
} else {
  console.log("I'm not a number");
}

to call Math.sign with number.

Since 1 positive, Math.sign returns 1.

If a number is negative, it returns -1.

If the number is positive zero, returns 0.

If the number is negative zero, returns -0.

Otherwise, NaN is returned.

Conclusion

To check if a number is negative with JavaScript, we use the Math.sign method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.