re: We don't need a ternary operator VIEW POST

FULL DISCUSSION
 

IMO (in JS at least), binary operator use for non-binary are good if you know what you're dealing with.

const a = b || default; // Fallback to default if b is not set or falsy !!!

const a = condition && b; // Take the value of b when condition is truthy

const a = (condition && b) || c; // Yay, one-line conditionnal
 // Take the value of b if truthy or fallback to c if falsy

I took care to write "falsy" and "truthy" because:

return data.filter(something) || "fallback"; // never get to fallback

But when filter is empty, it should have took "fallback" ?

Yes, but empty array [] is truthy.

But you should never care about the number of lines you write. Ninja coder can write this methods in 1 lines ? Whatever, I'll use 10 lines and have a clear code-base.

const filteredBySomething = data.filter(something);
if (!filteredBySomething.length) {
  return "fallback";
}
return filteredBySomething;
 

But in (condition && b) || c, if condition were true and b were false (or zero), it would return c. So that's not a correct implementation of a ternary operator.

 

Indeed, that's part of my point. You can do without ternary with some trickery, but best solution is to split it into real if else over multiple lines.

code of conduct - report abuse