r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

Show parent comments

-4

u/OmgImAlexis Nov 10 '20

What errors? If you’re using a good editor like VS code you shouldn’t have any issues guessing here.

if(typeof myFunction === ‘function’)

This reads better than what the OP shows. Without needing to know anything else I can read that it’s checking it’s a function. The ?. doesn’t.

The only time I can see it being a benefit is when you’re using a ternary operator to set something inline.

6

u/recycled_ideas Nov 10 '20

The Elvis operator on a function says "if this exists, call it", just like when you use it to get a property of an object that might be null or undefined.

Just because the operator is unfamiliar to you, doesn't mean it's bad. It just means that it's unfamiliar.

if(typeof myFunction === ‘function’)

Is significantly longer and says exactly the same thing.

Again, unfamiliar doesn't mean bad.

-7

u/OmgImAlexis Nov 10 '20

No. I’m not “unfamiliar” with it. It’s been in typescript for quite some time now. I actively disallow it.

Just use an if and test the access properly.

6

u/dertrommler06 Nov 10 '20

Why fight language improvements? Do you disallow spread because you’re used to Object.assign? Or mutate vars inside for loops instead of Array.map? I assure you if you use optional chaining you’ll find it reads far easier especially when accessing deeply nested properties on objects. 4 props or more deep is pretty hideous with &&