Categories: Development

Checking for undefined and null in Javascript

Undefined and null are values in JavaScript that represent the absence of a value or a variable being set.

While they may seem similar they do have different meanings and behaviour. Here are some methods on how to check for undefined and null in JavaScript.

Checking undefined

Undefined is a data type in JavaScript that represents the absence of a value, it is often returned when a variable or object property has not been assigned a value.

To check if a variable or object property is undefined, you can use the type of operator or the comparison operator.

if (typeof something === 'undefined') {
    //Its undefined
}

if (something === undefined) {
    //Its undefined
}

The above uses the type of comparison first and then the comparison operator. Type of is used for strict equality to the string ‘undefined’

if (typeof something === 'undefined') {
    //It is undefined
}

Checking null

Checking for null in Javascript requires a simple and common conditional statement

if (something === null) {
    //It is null
}

if (something !== null) {
    //It is NOT null
}

Check for both undefined and null:

if( typeof something === 'undefined' || something === null ){
    //Undefined OR null
}

In Javascript null does NOT equal undefined strictly however, it does after conversion equal (==).

null == undefined //true
null === undefined //false

 

Share
Tags: JSWeb Dev

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago