Optional Chaining ?. in JavaScript, and Nullish ?? operator ES2020
2 min readApr 6, 2021
This is amazing new feature of Objects and Arrays introduced in ES2020, it works on concept of Nullish Coalescing operator which was also introduced in ES2020.
for ex: we have an object openingHours inside an object restaurant and we want to display some value or result from that openingHours by first checking if that exist:const restaurant = {
name: 'casa la vista',
openingHours: {
thu: {
open: 12,
close: 22,
},
fri: {
open: 11,
close: 23,
},
sat: {
open: 0,
close: 24,
}
}
}// what we will do in old way is:if(restaurant.openingHours.mon){
console.log(restaurant.openingHours.mon.open)
} else {
console.log('Day doesn't exist')
}
output: Day doesn't exist
But with Optional chaining and nullish coalescing operator we can do it in lesser syntax and in very simple way 👉
console.log(restaurant.openingHours.mon?.open);
output will be: undefined;
because restaurant.openingHours.mon doesn't exist.// without optional chaining ?.
console.log(restaurant.openingHours.mon);
output will be: TypeError.
And here comes the use of Nullish operator ?? 👉
console.log(restaurant.openingHours.mon?.open ?? 'Does not Exist');
output will be: Does not Exist;//if we want to print other which exists:console.log(restaurant.openingHours.thu?.open ?? 'Doesn't Exist');
output will be: 12
// because the value exist in restaurant.openingHours.thu
So we have seen that it has saved lot of o syntax and it’s very handy and easy way.