A good[ish] website
Web development blog, loads of UI and JavaScript topics
A short an sweet guide into optional chaining operator ?.
in JavaScript.
It’s good to know that you can go one level deep in an object:
const foo = {}
console.log(foo.bar) // undefined 👍
But not more:
console.log(foo.bar.baz)
// ❌ Uncaught TypeError: Cannot read properties of undefined
Same here with a deeper object and null values, for example:
let foo = {
bar: {
baz: null
}
}
// This will crash: ❌ Uncaught TypeError: Cannot read properties of nullconsole.log(foo.bar.baz.quix)
Before optional chaining you would’ve maybe used Lodash get()
or such:
console.log(_.get(foo, 'bar.baz.quix.zot'))
This is when we can use the ?.
syntax:
console.log(foo.bar.baz.quix?.zot) // undefined
Now it returns undefined
and your program won't crash.
It also works with functions methods:
let string = null
console.log(string?.trim())
Or you can test if a method exists, like a callback function etc:
const someFunctions = (foo, callback) => {
// Do something...
return callback?.()
}
// Now it doesn’t error if called without the callback fn
someFunction('Foo bar')
It also works when getting object values using the bracket notation:
let foo = {
bar: null
}
let key = 'baz'
console.log(foo.bar?.[key]) // undefined
Or array index, this doesn’t do much, because calling an index that doesn’t exist does’t error out. Nonetheless, it’s works:
let foo = [1, 2, 3]
console.log(foo?.[3]) // undefined
One thing to keep in mind is that extensive usage of the optional chaining operator might add some weight to your bundles. Below is a screenshot from Babel compiler, where you can see that the transpiled code is much larger than the original.
I’d avoid using the optional chaining operator if not needed, for example in this case, only the last ?.
is needed.
Comments would go here, but the commenting system isn’t ready yet, sorry.