How to determine if the variable is undefined or null in JavaScript? The easiest way is to check if the variable is null. As null == undefined, checking for null indirectly also checks for undefined. To determine if the variable is null or undefined in AngularJS click here.
In this blog, we will see 4 different ways of to determine if the variable is undefined or null. The demo is available on JSFiddle.
- Method 1
The basic way is to check for null. As null == undefined, checking for null indirectly also checks for undefined.
[code language=”javascript”]
var name="yoUVcode";
if (name== null){
// your code here
}
[/code]
- Method 2
Check if the variable is initialized or not.
[code language=”javascript”]
var name="yoUVcode";
if (!name){
// your code here
}
[/code]
- Method 3
This will work for any variable that is either undeclared or declared and explicitly set to null or undefined. Else condition will be executed for a non null value.
[code language=”javascript”]
var name="yoUVcode";
if (typeof name=== ‘undefined’ || name === null){
// your code here
}
[/code]
- Method 4
Check if the value is undefined. This is similar to Method 1. As null == undefined, checking for undefined indirectly also checks for null.
[code language=”javascript”]
var name="yoUVcode";
if (name === undefined){
// your code here
}
[/code]
The complete demo is available on JSFiddle. To check if the JavaScript Object / Array is empty or not click here.
