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