Write All If Statement as If Expression
In JavaScript and language that borrows C syntax, there's “if expression”, often called ternary expression.
Example:
if ( x === 1 ) { x = 2; } else { x = 3; }
vs
( x === 1 ? x = 2 : x = 3 )
the if expression has all the advantages:
- expression advantage. You can grab it and place it anywhere.
- syntactic advantage. If you add parens, to each part or the whole, then there's a correspondence between syntax and semantic on units. You can easily grab and part and put elsewhere.
What if you write all if statements as if expressions (test ? trueExpr : falseExpr )
After experimenting for a few months, here's what i found.
Problems
Problem: ugly null in else
sometimes you want if without else. That means, you have to write (test ? trueExpr : null )
, which is ugly.
Problem: statements as expression
in JavaScript, often you need to write code that are statements with no
expression form, particularly with DOM.
(for example, see JavaScript: DOM Methods)
This means, you have to contort to make statements into expressions,
such as by making them a function and eval it right away, like this:
(() => { statement1; statement2; etc })()
. This bloats your source code and makes it significantly harder to understand.
Problem: unreadable nested if
When the if expression is nested 3 or more levels, it becomes impossible to read, no matter how you indent it.
( ( test ) ? ( ( test ) ? some : thing ) : ( ( test ) ? x : y ) )
Conclusion
Due to the bad syntax, and JavaScript and DOM are not particularly designed for functional programing, forcing all branch control into if expressions creates very convoluted code and is hard to read, to the degree that it outweight the advantages.