Optional Chaining in JavaScript


Do you want to make your code shorter and more readable?

In 2017, TC-39 introduced a new proposal for optional chaining in JavaScript addressing a common pain point. It shortens code and it conveys intent much better than current methods of handling the mechanism. The syntax is as follows:

// we receive person from somewhere and need to get the person's father's age
const age = person?.father?.age

What this solves

When you receive data from a database or user input, you won't always be 100% sure that object properties exists. Thus, the equivalent of the above assignment would be something like this.

if(person && person.father){
    var age = person.father.age

For you lodash fans, you may use something like this:

const age = _.get(person, 'father.age')

** Why am I doing doing all this checking? **

If you were to directly assign the variable without checking, it would through an error.

const person = new FatherLessPerson()
const age = person.father.age // Error! Cannot read property 'age' of undefined

What about default values?

Assigning default values should be doable with the following format:

Old way

// old way assigning -1 as a default value
const age = (person &&
             person.father &&
             person.father.age) ?
             person.father.age : -1

New way

// so shorter
const age = person?.father?.age || -1


We've not reached the point of having default Babel or browser support for optional chaining quite yet, but I think this functionality is a no-brainer. If the decision makers become conservative, progress may slow down, but this will be a useful language feature.

You may also like