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?
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 } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With