DEV Community

Discussion on: Avoid use IF on our JS scripts

Collapse
 
blindfish3 profile image
Ben Calder

Some useful suggestions here; but some should come with health warnings:

  • even a single nested ternary can be hard to read. Your example with multiple nesting should never get through code review. Nesting ternaries should be discouraged
  • short circuit can be useful; but can often result in mistakes: e.g. returning false when another type is expected (this is a good use for ternary). Linting rules often disallow conditionIsTrue && functionCall() outside an assignment expression.
  • the itemDropped example would work better using guard expressions: you still use if but can get rid of the redundant use of else. Simpler and more readable than your suggestion.
Collapse
 
vankatakisyov profile image
Ivan

The nested ternary hurts my brain, despite that, the article has a lot of gems, thanks guys!

Collapse
 
damxipo profile image
Damian Cipolat

hahaha yes is hard to process I know, but are just examples, the idea is to open the brain to new alternatives some very nice other heavy to understand.

Collapse
 
jankowskij profile image
JJankowski

I totally agree that nested ternaries are a pain to read.

Also, the itemDropped sample looks very "magical" to a person not familiar with such paradigm.

Collapse
 
damxipo profile image
Damian Cipolat

Well the idea is to provide reason to star going deeper in JS.

Collapse
 
damxipo profile image
Damian Cipolat

I am glad to see that it generates reactions in other devs, it is the idea of ​​the article. As I said above, the idea is not to stop using if it's just something to shake them and they can think about decisions in another way.

Collapse
 
blindfish3 profile image
Ben Calder

Generating reactions is all well and good, but I think it would be more productive to put forward examples of alternatives to if in contexts where they are appropriate/useful. Given the introduction describing code with too many ifs; some junior devs may mistakenly believe all your solutions represent good practice...

Thread Thread
 
damxipo profile image
Damian Cipolat

In the header it says that they are clearly techniques and you should not go into paranoia. Maybe in future articles I will raise 'real' situations I am collecting many situations with many sentences of my work, but at the moment I do not have enough time to do something at that level.