I came across this way of retrieving values from JavaScript objects when I was looking for an alternative for the Lodash get function.
It allows you to conditionally access values from an object if they exist, and returns undefined rather than an error if not.
Consider this piece of code:
const cartoon = {
name: 'Postman Page',
helper: {
animal: 'cat'
}
};
const helperAnimal = cartoon.helper?.animal;
console.log(helperAnimal)
// expected output: cat
const helperName = cartoon.helper?.name;
console.log(helperName);
// expected output: undefined
Rather that throwing an error when calling helperName, the question mark allows the key to be explored.
I find this incredibly helpful when you are not sure if a key/value exists, and don’t want to break your piece of code.
Top comments (0)