Optional Chaining in JavaScript
Have you ever had to check for the existence of objects or arrays before accessing its properties using && ?
const player = '{ "boots": { "size": 7, "color": "red" } }' if(player && player.boots && specimen.boots.size > 8) { console.log("Normal size"); }
The above statement checks if player object exists and if boots exists under player and then size exists under boots. This feature (or should I call it a workaround) lets us handle undefined or null easily. Now JavaScript is making it official with an operator ?.
Optional Chaining
Optional Chaining allows us to check if an object exists before trying to access its properties. The optional operator ?. if whatever is to the Left-Hand Side of ?.
is null
or undefined
. If it is, then the expression short-circuits and returns undefined
. Otherwise, the expression continues to evaluate as if nothing is wrong.
const player = '{ "boots": { "size": 7, "color": "red" } }' var size = player?.boots?.size;
Optional Chaining operator can also be used with functions and arrays.
var size = player?.boots?.size[0]; var color = player?.boots?.getColor();
1 Comment »