What is Optional Chaining in JavaScript?
Robert Marshall
Posted on June 22, 2020
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.
๐ ๐ช ๐
๐ฉ
Robert Marshall
Posted on June 22, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.