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

-6

u/OmgImAlexis Nov 10 '20 edited Nov 10 '20

It’s harder to read the intent and doesn’t add anything helpful for the few chars it saves.

6

u/threeys Nov 10 '20

I think one could make the case it adds value by reducing the need to repeat the same name twice, thus reducing the potential for errors.

I'm not sure it's worth it given how nontraditional it is, and I think JS devs typically do not think of functions as objects as it is being used here, but still it's an interesting approach

-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.

5

u/threeys Nov 10 '20

this example is a bit contrived:

const funcA = () => true;
const funcB = () => false;
const value = funcA && funcA();

I could accidentally change it to

const value = funcA && funcB();

and intellisense would be none the wiser.

This specific scenario isn't all that convincing, but IMO in general it's safer to be more expressive with less repetition than not, because it reduces the opportunity for subtle errors in the future.