Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like the swift optional chaining in javascript?

Tags:

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?

like image 301
MonkeyBonkey Avatar asked Nov 17 '15 13:11

MonkeyBonkey


2 Answers

Optional chaining has now been added to the language using the same ?. syntax as Swift, so I recommend doing it that way unless you need to support older browser versions.

If you do, I've written a function that handles this:

function getSafe (func) {     try {         return func()     } catch (e) {         if (e instanceof TypeError) {             return undefined         } else {             throw e         }     } } 

Call it like this:

if (getSafe(() => params.profile.address.default)) 

This works because by wrapping it in an anonymous function, it isn't evaluated until the try/catch block, which will then catch the error and return undefined if any of the parent properties are undefined.

Checking whether e is a TypeError prevents it from swallowing any other errors the function might throw so those can still be handled as needed. If you want it to just return undefined on any error, you can remove that part:

function getSafeNoErrors (func) {     try {         return func()     } catch {         return undefined     } } 
like image 63
John Montgomery Avatar answered Oct 04 '22 21:10

John Montgomery


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

like image 23
Dokinoki Avatar answered Oct 04 '22 20:10

Dokinoki