How to Check If Object Property is Null or Undefined in JavaScript ?
let obj = {
name : 'Hari',
info : {
country : 'India'
}
}
In the above code, obj.name
returns Hari
since the key name
exists. If you try to access a non existent key from obj
, like, obj.info.gender
it will throw undefined
.
Now let’s say if the value of gender
is undefined
since it doesn’t exists we need to show some default value, like Not specified
. You can do,
let obj = {
name : 'Hari',
info : {
country : 'India'
}
};
let gender = obj.info && obj.info.gender ? obj.info.gender : "Not specified";
Now let’s rewrite the above checking using Optional Chaining,
let obj = {
name : 'Hari',
info : {
country : 'India'
}
};
let gender = obj.info?.gender ?? "Not specified";
And at the end we have used ??
(Nullish Coalescing Operator) to check if null or undefined and in such cash return a default value.