News for hackers. Stuff that matters.
Re:Writing Eloquent JavaScript Without CoffeeScript by raganwald on Friday December 09, 2011 @11:13AM (#3334207)
For the sake of a productive discussion, two of the things mentioned about converting ifs to ternaries _could_ be used to create better code.

The ternery operator has some readability problems, but it is an expression, not a statement. Turning statements into expressions is powerful, which is why CoffeeScript's if/then compiles into an expression. Too bad this wan't mentioned.

Likewise, the comma operator allows JavaScript programmers to use a block of consecutive statements as an expression, something the author points out when explaining how to use ternaries in place of if statements.

The notion that you can use a sequence of statements as an expression without having to resort to a "let" form (function () { ...; ...; ...; return foo; })() is another underused construct that can make for improved JavaScript.

Put the two ideas together, and yes you can express a multi-line if statement with shorter keywords, but more importantly you have an if expression without having to wrap it in a function and encumber it with return statements.

I'm sorry that idea wasn't given more attention. If you aren't using JavaScript directly, this pattern may be useful in a more functional, expression-oriented style of programming.

There are no comments on this comment yet.