DEV Community

loading...

Discussion on: Prevent Object Retrieval TypeError with &&

Collapse
drbearhands profile image
DrBearhands

Why would one prefer the && operator over a conditional? At first glance, the later seems 'better' in many ways:

  • closer to truth
  • less language-dependent, especially if you use if (x.y !== undefined)
  • better control flow, as x.y && will result in undefined if x.y is undefined, rather than entering an else clause

It's a one-liner, sure, but I would argue ternary operators are a better fit: x.y ? f(y) : g() over (x.y && f(y)) || g().

Not saying you're wrong, but I'm curious about the reasoning.

Collapse
hjess profile image
Howard Jess

I'm in agreement with those opposing this idiom. The Javascript phrase:


obj && obj.prop && obj.prop.send();

is an expression, and (to me at least) should be pure, like a pure function. As used above, this expression is used only for its side effect. I would always prefer to be explicit. I like the proposed optional chaining; but until that's available, write this statement in English:


// pedantic
if (obj && obj.prop && typeof obj.prop.send === 'function') {
obj.prop.send();
}

Collapse
samanthaming profile image
Samantha Ming Author • Edited

That’s the really interesting thing about JS or programming in general. There are always multiple ways of solving things. Some of them are definitely a syntactic choice. I’m always in the camp of expanding my toolkit so when I run across it (especially from others code), I know what’s going on. But at the end of the day, you’re the owner of your code, so pick the way that makes the most sense to you 😊