Check if a Value Is Null or Undefined in JavaScript or Node.js

JavaScript uses two representations of „empty“ values. When „empty“ we mean that they don’t have an exact value assigned. These two values are null and undefined.

Both values, null and undefined, are valuable in JavaScript. Except when you are not checking for them. In such cases, you’re running into errors where you’re not able to access a property or method on “null” or “undefined”.

This tutorial shows you how to check whether a given value is either null or undefined.

Node.js Series Overview

Detect Null or Undefined Values in JavaScript

You can create a utility method checking whether a given input is null and undefined. Here’s a sample function that you may copy to your project and is it to check for empty values:

/**
 * Determine whether the given `value` is `null` or `undefined`.
 *
 * @param {*} value
 *
 * @returns {Boolean}
 */
function isNullOrUndefined (value) {  
  return value == null

    // `value == null` is the same as `value === undefined || value === null`
}

The value == null comparison is a handy way to check for null and undefined simultaneously. The loose equality operator attempts to convert and compare operands of different types.

Using the „@supercharge/goodies“ Package

I’m the maintainer of the @supercharge/goodies package providing convenient helper functions for Node.js and JavaScript. This package comes with a handy isNullish(value) method determining whether the given value is null or undefined:

const { isNullish } = require('@supercharge/goodies')

isNullish(null)  
// true

isNullish(undefined)  
// true

isNullish(0) // false  
isNullish('') // false  
isNullish({}) // false  
isNullish([]) // false  
isNullish(false) // false  

Notice: the isNullish method is fully typed and your code editor or IDE knows that the provided value is either null/undefined or not. The typing happens because the @supercharge/goodies package is written in TypeScript and provides proper typing for the isNullish method.

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.