JavaScript, what happens if you write all if-statement as if-expression (2015)

By Xah Lee. Date: . Last updated: .

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:

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
sucks
warts