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 xx;
if (3 > 2) {
 xx = "yes";
} else {
 xx = "no";
}

console.log(xx);
// yes

// if-expression
let yy = (3 > 2) ? "yes" : "no";
console.log(yy);
// yes

the if expression has the Expression advantage: You can embed and move it in any expression.

What if you write all if-statements as if-expressions

After experimenting for a few months, here's what i found.

Problems

Problem: statements as expression

in JavaScript, often you need to write code that are statements with no expression form, particularly with DOM. (for example, JS DOM: Create / Insert HTML Element )

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");

Problem: ugly null in else

sometimes you want if without else. That means, you have to write

(test ? true_expr : null )

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.