How To Check if Value Is A Negative Number In JavaScript

Check if Value is a Negative Number in JavaScript

In JavaScript we have many functions can already check if value is a negative number. Today we will introduce two ways to do that. Each approach is relatively straightforward, so you can use whichever you want.

Check if value is a negative number in JavaScript

Using Math.sign()

Syntax:

Math.sign(value)

Parameter:

  • value: The value to check, can be a string or a number.

The Math.sign() function answers whether a number is negative or not by the returned value. If the returned value is 1, then it is not negative. Otherwise, the returned value is -1 indicates that the number passed to the function is a negative number. For example:

// Check if a string is a negative number
let string = "-123456";
console.log(Math.sign(string));

// Check if a number is a negative number
let number = -123456;
console.log(Math.sign(number));

Output: 

-1
-1

This method is easy to understand. As long as the string (or number) we are checking is a valid negative number, the method returns -1. That is exactly the value we are looking for. In addition, if the string is “0” or the number is zero, this method will return 0. 

Using binary < operator

Syntax:

a < 0

Parameter:

  • a: The value to be checked can be in type number or string.

We have learned in our school that any negative number is smaller than zero. Hence we can use the smaller than (<) operator to check if that value is a negative number or not. For instance:

// Check if a string is a negative number
var string = "-123456";
console.log(string<0);

// Check if a number is a negative number
var number = -123456;
console.log(number<0);

Output:

true
true

As you can see, using this operator is familiar to you because this math operator has been used many times in practice. You should also know that most programmers enjoy using this solution more than others. However, there are still some other approaches to solve this problem, but we don’t recommend you use them because the solutions provided in this tutorial are the most optimized ones.

Summary

We have learned how to check if value is a negative number in JavaScript. Although there are many ways to do that, we still recommend using the binary < operator because it is the quickest method.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *