JavaScript, what happens if you write all if-statement as if-expression (2015)
In JavaScript, you have if-statement and if-expression. (if-expression is often called ternary expression.)
Example:
// if-statement let x = 1; if (x === 1) console.log("yes"); else console.log("no"); // if-expression let y = 1; y === 1 ? console.log("yes") : console.log("no");
the if expression has all the advantages:
- Expression advantage. You can embed it in any expression.
- 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 copy/cut the part.
What if you write all if-statements as if-expressions
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 JS: DOM Methods)
This means, you have to contort to make statements into expressions, such as by making them into a function and eval it right away, like this:
// trick to turn statements into a expression ((x) => { // statement 1 // statement 2 // 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.
const testA = true; const testB = false; testA ? (testB ? console.log("yes") : console.log("no")) : console.log("testA failed");
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.
JavaScript sucks
Spec Reading
- Reading JavaScript spec notes (2015)
- JavaScript Grammar is Not Context-Free (2016)
- JavaScript Syntax Complexity: Lookahead (2015)
- JavaScript sort, is fragile, and most complex, convoluted (2017)
- JavaScript Spec, Term “instance” is Not Defined (2017)
- JavaScript Spec Change on Date Time Zone Default (2022)
- The term INSTANCE in Object Oriented Programing
sucks
- JavaScript Warts
- JavaScript is Truly Bad Language (2025)
- JavaScript Sucks. Variations of Looping Thru Array (2025)
- Xah JavaScript Style Guide for FP
- JavaScript, what happens if you write all if-statement as if-expression (2015)