What is optional chaining?
In Js you can access properties of an object using '.'
or ['property_name']. For example:
let a = { b: 50 };
console.log(a['b']) // logs 50
console.log(a.b) // logs 50
But there can be instances where the property does not exists or the value is null.
For example, In JavaScript, the values null and undefined are the only two values that do not have properties.
And when accessing properties of null or undefined will throw a Type Error. Like the below code:
let a = { b: null };
a.b.c.d
// => Uncaught TypeError: Cannot read properties of null (reading 'c')
To gracefully handle such type errors, we use optional chaining.
Notice the use of ? in the below code.
let a = { b: null };
a.b?.c.d
// => undefined
a is an object, so a.b is a valid property access expression. But the value of a.b is null, so a.b.c would throw a TypeError. By using ?. instead of . we avoid the TypeError, and a.b?.c evaluates to undefined.
What is short circuiting?
The term short-circuiting generally refers to an electric short circuit, which means that the electric current took a short-cut to reach at a particular point rather than taking the intended path.
Here in Js, it has a similar intention.
Let's understand through a code example:
let a = { b: null };
a.b?.c.d // undefined
(a.b?.c).d // Type Error
Note that the first code block is (without the parenthesis)
simply evaluates to undefined and does not throw an error. This is because property access with ?. is “short-circuiting”
i.e. immediately reaching to the final result instead of following the intended property access.
Where as the second code block will be evaluated entirely no matter what.
If the subexpression to the left of ?. evaluates to null or undefined, then the entire expression immediately evaluates to undefined without any further property access attempts. Hence, the code block short circuited.
Next, we will look into conditional method invocation.
Thank you for reading my blog, any suggestions / comments / likes / dislikes are appreciated.
Top comments (0)