DEV Community

Discussion on: Do we even need if/else?

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Having a chained ternary is not always wrong. Chaining them more than 2 or 3 times are usually wrong because you'll rely on checks that are dependant on each other and you'll probably need different chained ternary blocks to reach the expected use cases so it's better to use if/else but

foo === "x" ? doSomething : foo === "z" ? doSomethingElse : fallback;
Enter fullscreen mode Exit fullscreen mode

There's nothing wrong here as long as this covers your use cases properly. If you don't need the fallback then this is wrong but if this is just what you need then go ahead with that, we should be fine.

const otherCases = foo => (foo === "z" ? doSomethingElse : fallback);

const example = foo === "x" ? doSomething : otherCases(foo);

example(value)();
Enter fullscreen mode Exit fullscreen mode

This is supposed to be equivalent to the code above but instead you add a function declaration and a variable to reach... pretty much the same?
This is absurd. An extreme lack of knowledge about logic gates and inefficient way of working just because "you like how it looks".

Then here

foo ? doSomething() : undefined;
Enter fullscreen mode Exit fullscreen mode

Why should you state "undefined" just because foo is falsy?
You are not even setting this value into a variable to check later (it can be ok depending on the use case). instead you're just saying:

if (foo) doSomething();
else undefined;
Enter fullscreen mode Exit fullscreen mode

The question now is... undefined what? What's the point? What should we do with this undefined?

Again your starter point is "I like how it looks" not an understanding on how things work below.