clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Optional chaining operator in JavaScript

Filed under: JavaScript— Tagged with: es2020

A short an sweet guide into optional chaining operator ?. in JavaScript.

Which problem optional chaining addresses?

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'))

Optional chaining operator

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.

Optional chaining with functions

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')

With bracket notation

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

Conclusions

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.

Screenshot of the Babel REPL
Optional chaining operator code transpiled

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @intterne if you want to make a correction etc.

  • © 2022 Antti Hiljá
  • About
  • Follow my new Twitter account → @intterne
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!