JavaScript check if a number is negative or not using check-more-types library

In this JavaScript tutorial we learn how to use the check-more-types module to check if a number is a negative number or not using negative() or negativeNumber() method of the check-more-types module.

Create the sample project

Firstly we create an empty project with the following command.

mkdir sample-project
cd sample-project
npm init -y

And install the check-more-types module using the following command.

npm install check-more-types --save

How to check a number is negative in JavaScript

To check whether a given number is a negative number or not we can use the negative(), negativeNumber(), not.negative() or not.negativeNumber() method of the check-more-types library. The negative() and negativeNumber() method returns true ì the argument value is negative number. The not.negative() and not.negativeNumber() method returns true if the provided argument is not a negative number.

In the sample-project directory create a new file named check-negative.js as below.

check-negative.js

var check = require('check-more-types');

console.log(check.negative(-10));
console.log(check.negative(10));

console.log(check.negativeNumber(-10));
console.log(check.negativeNumber(10));

console.log(check.not.negative(-10));
console.log(check.not.negative(10));

console.log(check.not.negativeNumber(-10));
console.log(check.not.negativeNumber(10));

Run the check-negative.js file using the following command.

node check-negative.js
The output is:
true
false
true
false
false
true
false
true

More examples of how to use the check.negative() and check.negativeNumber() method

check-negative-example.js

var check = require('check-more-types');

var number1 = -9;
var number2 = 9;
var number3 = -200;
var number4 = 300;

if(check.negative(number1)) {
    console.log(number1 + ' is a negative number.');
}

if(check.negative(number2)) {
    console.log(number2 + ' is a negative number.');
}

if(check.not.negative(number1)) {
    console.log(number1 + ' is not a negative number.');
}

if(check.not.negative(number2)) {
    console.log(number2 + ' is not a negative number.');
}

if(check.negativeNumber(number3)) {
    console.log(number3 + ' is a negative number.');
}

if(check.negativeNumber(number4)) {
    console.log(number4 + ' is a negative number.');
}

if(check.not.negativeNumber(number3)) {
    console.log(number3 + ' is not a negative number.');
}

if(check.not.negativeNumber(number4)) {
    console.log(number4 + ' is not a negative number.');
}

Run the check-negative-example.js file using the following command.

node check-negative-example.js
The output is:
-9 is a negative number.
9 is not a negative number.
-200 is a negative number.
300 is not a negative number.

Happy Coding 😊