JavaScript: Check if Variable is undefined or null

JavaScript: Check if Variable is undefined or null

Introduction

undefined and null values sneak their way into code flow all the time. Whether we lose a reference through side-effects, forget to assign a reference variable to an object in memory, or we get an empty response from another resource, database or API - we have to deal with undefined and null values all the time.

In this short guide, we'll take a look at how to check if a variable is undefined or null in JavaScript.

Difference Between undefined and null

undefined and null variables oftentimes go hand-in-hand, and some use the terms interchangeably. Though, there is a difference between them:

  • undefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything.
  • null is a variable that is defined but is missing a value.

The difference between the two is perhaps a bit more clear through code:

let a;
console.log(a); // undefined

let b = null;
console.log(b); // null

a is undefined - it's not assigned to anything, and there's no clear definition as to what it really is. b is defined as a null-value.

Whether b was straight up defined as null or defined as the returned value of a function (that just turns out to return a null value) doesn't matter - it's defined as something.

On the other hand, a is quite literally nothing. No assignment was done and it's fully unclear what it should or could be.

In practice, most of the null and undefined values arise from human error during programming, and these two go together in most cases. When checking for one - we typically check for the other as well.

Check if Variable is undefined or null

There are two approaches you can opt for when checking whether a variable is undefined or null in vanilla JavaScript.

== and === Operators

There's a difference between the Loose Equality Operator (==) and Strict Equality Operator (===) in JavaScript. Loose equality may lead to unexpected results, and behaves differently in this context from the strict equality operator:

console.log(null == undefined);  // true
console.log(null === undefined); // false

Note: This shouldn't be taken as proof that null and undefined are the same. The loose equality operator uses "coloquial" definitions of truthy/falsy values. 0, "" and [] are evaluated as false as they denote the lack of data, even though they're not actually equal to a boolean.

That being said - since the loose equality operator treats null and undefined as the same - you can use it as the shorthand version of checking for both:

// Undefined variable
let a;

if (a == null) {
  console.log('Null or undefined value!');
} else {
  console.log(a);
}

This would check whether a is either null or undefined. Since a is undefined, this results in:

Null or undefined value!

Though, we don't really know which one of these is it. If we were to use the strict operator, which checks if a is null, we'd be unpleasantly surprised to run into an undefined value in the console.log() statement:

let a;

if (a === null) {
  console.log('Null or undefined value!');
} else {
  console.log(a); // undefined
}

a really isn't null, but it is undefined. In this case, we'd want to check them separately, but have the flexibility of knowing the real reason for the flow:

let a;

if (a === null || a === undefined) { // true
  console.log('Null or undefined value!');
} else {
  console.log(a);
}

Here, we've combined them together with an exclusive OR - though you can separate them for different recovery operations if you'd like to as well:

let a;

if (a === null) {
  console.log('Null value!');
} else if (a === undefined) { // true
  console.log('Undefined value!');
}

Note: It's worth noting that if the reference doesn't exist, a ReferenceError will be thrown. This can be avoided through the use of the typeof operator, though it might not be the best choice from the perspective of code design. If you're using a non-existent reference variable - silently ignoring that issue by using typeof might lead to silent failure down the line.

typeof Operator

The typeof operator can additionally be used alongside the === operator to check if the type of a variable is equal to 'undefined' or 'null':

let a;

if (typeof a === 'undefined') {
    console.log('Undefined variable');
} else if (typeof a === 'null') {
    console.log('Null-value');
}

This results in:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Undefined variable

However, it's worth noting that if you chuck in a non-existing reference variable - typeof is happy to work with it, treating it as undefined:

if (typeof someVar === 'undefined') {
    console.log('Undefined variable');
} else if (typeof someVar === 'null') {
    console.log('Null-value');
}

This code also results in:

Undefined variable

Technically speaking, some_var is an undefined variable, as it has no assignment. On the other hand, this can make typeof silently fail and signal that the incoming value might have an issue, instead of raising an error that makes it clear you're dealing with a non-existing variable.

For instance - imagine you made a typo, and accidentally input somevariable instead of someVariable in the if clause:

let someVariable = 'Hello!'

if (typeof somevariable === 'undefined') {
    console.log('Undefined variable');
} else if (typeof somevariable === 'null') {
    console.log('Null-value');
} else {
    console.log(somevariable);
}

Here, we're trying to check whether someVariable is null or undefined, and it isn't. However, due to the typo, somevariable is checked instead, and the result is:

Undefined variable

In a more complex scenario - it might be harder to spot this typo than in this one. We've had a silent failure and might spend time on a false trail. On the other hand, using just the == and === operators here would've alerted us about the non-existing reference variable:

let someVariable = 'Hello!'

if (somevariable === 'undefined') {
    console.log('Undefined variable');
} else if (somevariable === 'null') {
    console.log('Null-value');
} else {
    console.log(somevariable);
}

This code results in:

error: Uncaught ReferenceError: somevariable is not defined

Note: This isn't to say that typeof is inherently a bad choice - but it does entail this implication as well.

Using Lodash to Check if Variable is null, undefined or nil

Finally - you may opt to choose external libraries besides the built-in operators. While importing an external library isn't justified just for performing this check - in which case, you'll be better off just using the operators.

However, Lodash is already present in many projects - it's a widely used library, and when it's already present, there's no efficiency loss with using a couple of the methods it provides. Most notably, Lodash offers several useful methods that check whether a variable is null, undefined or nil.

Install and Import Lodash

You can import Lodash through a CDN:

https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js

Import it locally from a .js file:

<script src="lodash.js"></script>

Or install it via NPM:

$ npm install lodash

Furthermore, it can be imported as an ES6 module or imported via the require() syntax:

import _ from 'lodash';
// OR
const _ = require('lodash');

Note: It's convention to name the Lodash instance _, implied by the name, though, you don't have to.

Now, we can use the library to check whether a variable is null, undefined or nil - where nil refers to both of the previous two afflictions. It can be used as the shorthand version for checking both:

let a = null;

console.log(_.isNull(a));       // true
console.log(_.isUndefined(a));  // false
console.log(_.isNil(a));        // true

Conclusion

In this short guide, we've taken a look at how to check if a variable is null, undefined or nil in JavaScript, using the ==, === and typeof operators, noting the pros and cons of each approach. Finally, we've taken a quick look at using Lodash - a popular convenience utility library to perform the same checks.

Last Updated: November 25th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Getting Started with AWS in Node.js

    Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

    © 2013-2021 Stack Abuse. All rights reserved.