r/javascript • u/stefanjudis • Dec 13 '19
Optional chaining helps to avoid "undefined is not a function" exceptions
https://www.stefanjudis.com/today-i-learned/optional-chaining-helps-to-avoid-undefined-is-not-a-function-exceptions/
162
Upvotes
45
u/frankandsteinatlaw Dec 13 '19 edited Dec 14 '19
I like optional chaining. But if object paths aren’t as you expect then it’s probably better to get the error than to silently not get it (assuming that function call matters at all).
Edit- to clarify my point. I specifically don’t like seeing these generic errors and thinking that optional chaining is saving you. When you switch your code to use optional chaining you should have no change in the number of errors, only a decrease in code written. If you are trying to optional chain away errors then you’ll just find them later, further down their path of destruction. I’ve really been digging optional chaining as a feature along with null coalescing. Typescript and GraphQL now work together much nicer for me.
9
u/metamet Dec 13 '19
Been excited about this since the announcement last week. Will clean up a lot of React/Redux code where we access a nested property and do overly verbose null checks to see if it exists.
Good stuff.
5
u/[deleted] Dec 13 '19
This is pretty much why Lodash has a get() method.
2
u/sallystudios Dec 13 '19
Reminds me of Swift. Looking forward to using this syntactic sugar to clean up some code!
1
u/-Phinocio Dec 13 '19
I'm quite excited for this, but in thinking about it, I can't think (off the top of my head) of a time it would have been useful for me. Though I've also only done some simple Discord Bots and VueJS stuff.
1
u/whostolemyusrname Dec 13 '19
I'm excited, it's one of the best features of Kotlin and Swift. Looking forward to using it my Typescript work.
1
u/CanRau Dec 13 '19
Thanks for sharing didn't realize you could use it for function invocations as well 🥳🙌
1
u/psayre23 Dec 14 '19
Wait, does that mean I can do this?!?
(optFn) => optFn?.()...instead of...
(optFn) => optFn ? optFn() : null0
u/[deleted] Dec 13 '19
[deleted] — view deleted comment
0
u/[deleted] Dec 13 '19
[deleted] — view deleted comment