Learn how to effectively check if the value is undefined or not in javascript.
A variable or an object which is declared without any value is undefined
.
var apple; console.log(apple); //undefined. let banana = true; console.log(banana); //true
Using typeof operator to check undefined
The most prominent method is to use typeof
operator which returns the type of the object in string format.
We can use that to determine the value of any variable or object if it is undefined
or not.
var abc = "Prashant Yadav"; typeof abc; //'string' let xyz = 12; typeof xyz; //'number' let fix = true; typeof fix; //'boolean' let js; typeof js; //'undefined' const arr = []; typeof arr; //'object' const obj = {}; typeof obj; //'object' let ass = () => { return 'Hello'; }; typeof ass; //'function'
typeof
return 'undefined'
in string format if value is not declared.
let js; if(typeof js === 'undefined'){ console.log('undefined value'); } //'undefined value'
We can use the same for the objects and nested objects as well.
let obj = { x: 1, y: 2 }; if(typeof obj.z === 'undefined'){ console.log('z is not defined in obj'); } //'z is not defined in obj'
Directly checking undefined
value
In modern browsers you can directly check if the current variable is undefined or not in javascript.
let abc; if(abc === undefined){ console.log('I am undefined'); } //'I am undefined'
This will not work in older browsers and IEs so it is better to use the above method only.