How to check if a variable is undefined or NULL in JavaScript

To check if a variable is undefined or null in JavaScript, either use the equality operator == or strict equality operator ===.

In JavaScript, a variable is considered undefined if it is declared but not assigned a value. Whereas the null is a special assignment value that signifies 'no value' or nonexistence of any value:

let name
let age = null

console.log(name)    // undefined
console.log(age)     // null

The equality operator == (also called loose equality operator) provides a more concise way to check whether the variable is undefined or null:

let name // undefined variable

if (name == null) {
  console.log(`Name is either undefined or null`)
} else {
  console.log(`Name is NOT undefined or null`)
}

// Output => Name is either undefined or null

The condition name == null evaluates to true because the equality operator treats both undefined and null as the same:

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

Since the strict equality operator === (also called identity operator) does not treat undefined and null as the same, we have to use the || (or) operator to check if either of the two conditions is met:

let name

if (name === undefined || name === null) {
  console.log(`Name is either undefined or null`)
} else {
  console.log(`Name is NOT undefined or null`)
}

// Output => Name is either undefined or null

The strict equality operator === is more explicit but less concise as compared to the loose equality operator == for checking if the variable is undefined or null in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.