JavaScript check if an variable is defined or not using check-more-types library

In this JavaScript tutorial we learn how to check if a variable is defined or not using the defined() method of 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 variable is defined or not in JavaScript

To check if a given variable is defined or not we can use the defined() method of check-more-types library. The method returns true if the argument defined.

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

check-defined.js

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

console.log(check.defined(1));
console.log(check.defined(false));
console.log(check.defined(''));
console.log(check.defined(null));

console.log(check.defined());
console.log(check.defined({}.doesNotExist));

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

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

More examples of how to use the check.defined() method

check-defined-example.js

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

var test1 = "tori code";
var test2;

if(check.defined(test1)) {
    console.log('test1 is defined');
} else {
    console.log('test1 is not defined yet.');
}

if(check.defined(test2)) {
    console.log('test2 is defined');
} else {
    console.log('test2 is not defined yet.');
}

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

node check-defined-example.js
The output is:
test1 is defined
test2 is not defined yet.

Happy Coding 😊