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…
Continue reading “Optional Chaining Operator in JavaScript – Bene Studio”