r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

58

u/dudeitsmason Nov 10 '20

Just because you can, doesn't mean you should

0

u/[deleted] Nov 10 '20

[deleted]

0

u/Not_Sugden Nov 10 '20 edited Nov 10 '20

it really depends on the use case for me, but i rarely run into situations where an the chaining would look more logical than chaining x && x.y

like uh

const bool = x && x.y ? x.y : false;

const bool = x && x.y ? x.y === 'smth' : false;

rather than

const bool = x?.y || false;

const bool = x?.y === 'smth'

the 2nd example here is a better one, what use is it comparing undefined to a string, using a tenary w/ && would be more logical there no?

edit: this has no relevance but i just wanted to say

you could also do

const bool = Boolean(x) && (x.y === 'smth');

5

u/robotslacker Nov 10 '20

The optional chaining way looks much more readable.