Search code examples
javascriptswiftoption-type

Is there something like the swift optional chaining in javascript?


I've been doing a lot of code likes this in javascript

if (params && params.profile && params.profile.address && params.profile.address.default)

where I have to check for each optional, it gets pretty tedious. Is there a better way in javascript that's similar to how swift would deal with optionals, e.g.

if let checked = params?.profile?.address?.default?


Solution

  • There is no such operator in native JS.

    However, there is a Babel plugin that will accomplish that, please check https://github.com/davidyaha/ecmascript-optionals-proposal

    Also, please refer to Null-safe property access (and conditional assignment) in ES6/2015 for more references