News for hackers. Stuff that matters.
Re:Writing Eloquent JavaScript Without CoffeeScript by josephturnip on Friday December 09, 2011 @10:03AM (#3333901)
Using the ternary operator is more "eloquent" than conditionals? That's true iff "eloquent" means terse in terms of number of characters, but I find if(...){} much more readable.
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.

Re:Writing Eloquent JavaScript Without CoffeeScript by xer0 on Friday December 09, 2011 @11:50AM (#3334400)
"I find if(...){} much more readable."

Not only is it more readable, it's more correct in the example given.

"if" is a statement. The ternary operator (?:) is an expression, that returns a value. The semantics are different, and using the ternary operator "merely" to replace an if statement, especially where no assignment of the ternary operator's return value is made, is a code smell.

The ternary operator is great if you're replacing a simple "if something assignment to X else other assignment to X." Any other use is questionable.