Optional Chaining Operator in JavaScript – Bene Studio

  • var user = { name: ‘Joe’ } – var zip = user.address.zip // ⚡⚡⚡Uncaught TypeError: Cannot read property ‘zip’ of undefinedIn this example we expect user.address.zip to exist but for some reason the address is missing from the user object.
  • Workaround #1: Logic Expressionsvar user = { name: ‘Joe’ } – var zip = user – user.address – user.address.zipNoisy and verbose.
  • Workaround #2: Ternary Operatorsvar user = { name: ‘Joe’ } – var zip = – user === undefined – ?
  • Workaround #3: Try-Catchvar user = { name: ‘Joe’ } – var ziptry { – zip = user.address.zip – } catch (error) { – zip = null – }Breaks control and has own scopes.
  • bin/babel index.jsThe Transpiled CodeTranspiled version of the index.js above: – var _user$address;var user = { – name: ‘Joe’ – };var zip = – user == null – ?

All of us usually confronts the situation where an expected member of a property chain is undefined or null. In this example we expect user.address.zip to exist but for some reason the address is…

Optional Chaining Operator in JavaScriptOptional Chaining Operator in JavaScriptThe Problem of Property ChainingAll of us usually confronts the situation where an expected member of a property chain is undefined or null.

var user = { name: ‘Joe’ }

var zip = user.address.zip // ⚡⚡⚡Uncaught TypeError: Cannot read property ‘zip’ of undefinedIn this example we expect user.address.zip to exist but for some reason the address is missing from the user object.

Workaround #1: Logic Expressionsvar user = { name: ‘Joe’ }

var zip = user

user.address

user.address.zipNoisy and verbose.

Workaround #2: Ternary Operatorsvar user = { name: ‘Joe’ }

var zip =

user === undefined

? undefined

: user.address === undefined

? undefined

: user.address.zipEven more noisy and verbose.

Workaround #3: Try-Catchvar user = { name: ‘Joe’ }

var ziptry {

zip = user.address.zip

} catch (error) {

zip = null

}Breaks control and has own scopes.

Also a bit noisy.

Of course there are many workarounds, property selector libraries etc.

Optional Chaining OperatorThere is a new proposal for ECMAScript. It is currently in stage 1 and there are 4 stages.

var user = { name: ‘Joe’ }

var zip = user?.address?.zipVoilà, zip is undefined and does not throw an error.

The syntax…

Optional Chaining Operator in JavaScript – Bene Studio