3 ms·
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(...){} m
by josephturnip 15y ago
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.
- raganwald 15y agoFor 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.
- xer0 15y ago"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.