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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago