4 ms·
To each his own but I disagree. Nested ternary's are hard to read and understand, and modifying them (by future devs) is tricky and error prone.
by macspoofing 6y ago
To each his own but I disagree. Nested ternary's are hard to read and understand, and modifying them (by future devs) is tricky and error prone.
- deleted 6y ago[deleted]
- Stratoscope 6y agoTrue, nested ternaries can be hard to follow. And the excessive parentheses promote this way of looking at it. OTOH I think chained ternaries can be simple and easy to understand. Yes, they are the exact same thing in this case, but getting rid of those nested parens really helps, at least for me. sarah180's example is a good illustration. I would change the order of the tests because it makes more sense to me to check the min before the max. I'd also make one minor formatting change, because I code in a proportional font and can't line things up in columns: a < min ? min : a > max ? max : a Maybe people think differently, but to me that is super easy to understand, and much better than the confusing Math.min/max stuff. I would also wrap the whole thing inside a function: function clamp( value, min, max ) { return( value < min ? min : value > max ? max : value ); } Now that it's inside a function, you could change the code to use if statements, or Math.min/max, or whatever suits your preferences.