r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

84

u/anon774 Nov 10 '20

People are hating on this approach, but IMO the only reason people think this is bad or shows "unclear intent" is because it's new and they're unfamiliar with it.

It's extremely clear what this means, I don't know how you could get confused by this if you saw it in the code. Nobody has provided an example showing how this could be unclear.

1

u/HappinessFactory Nov 10 '20

It's definitely as clear as the alternative that was provided. But as a junior

if(cb){ cb(); }

Makes a hell of a lot more sense.

I use turnarys and other shortcuts like the rest of y'all but I still thing if statements are the king of readability.

4

u/[deleted] Nov 10 '20

Hard disagree, it's only more readable if your definition of readability is pinned to that of a beginner. As we become more knowledgeable our idea of readability should move with us.

Take this for example, beginners often don't know about ternaries:

const x = a ? b : c;

The more "readable" approach as you put it would be like this:

let x;
if (a) {
    x = b;
else {
    x = c;
}

Not only is this noisier and harder to parse for anyone more experienced but it's also opened up the need to track the mutability of the variable reference that didn't exist with the ternary approach.

1

u/SnerkDRabbledauber Nov 10 '20

As we become more knowledgeable our idea of readability should move with us.

Sounds like you don't have a clear grasp of the term "readability". The goal is to avoid confusion and make the meaning clear to the widest levels of skill you can while still making it fast to scan for all levels.

1

u/[deleted] Nov 10 '20

It's slower to scan for all but beginners. You must pick a lane.

And you likewise must define a bottom end to your skill gradient, else you couldn't even use let or const lest an absolute beginner not know of them. Or functions for that matter, beginners mightn't have gotten that far yet!