5 ms·
Sure, when you're neatly using booleans with names that are three characters long, this is super easy to parse. Now throw in long functions with multiple argum
by dimgl 5y ago
Sure, when you're neatly using booleans with names that are three characters long, this is super easy to parse.
Now throw in long functions with multiple arguments, and all kinds of different access patterns and this ternary starts to look like a nightmare.
- akvadrako 5y agoIt's still often the cleanest way and I find myself doing something like this: let x = somelongfunc(arg, blah(etc)) ? value1 : some other condition ? value2 : fallback What I usually want is pattern matching expressions, but those are not in many languages.
- brimble 5y agoTry as I might, I have to reason through ternaries every time I encounter them. I think the = being so removed from what it's actually assigning, but without grouping parens, is what messes me up. Plus I always forget what the punctuation characters mean—if/elseif/else uses words, so I don't have to remember.
- tobr 5y agoJust read whatever has a question mark after it with the intonation of a question, and it flows naturally.
- eyelidlessness 5y ago> I think the = being so removed from what it's actually assigning, but without grouping parens, is what messes me up. I almost always use grouping parentheses for this reason, unless it’s a very short single line expression. That said, if/else if/else has a different colocation problem: it puts the assignment further from the initial declaration, making its scope less obvious (unless you’re hoisting var, which is awful for its own reasons).
- brimble 5y agoAgree, the problem with if/else is that you end up having to consider the whole block plus usually a little context from just before it. I still find it much easier to read, unless very poorly written, while all ternaries slow me down every single time I read one, no matter how well-written. I struggle to parse them into ideas and words and to follow the order of events, seemingly no matter how many times I encounter them. They just feel wrong. All that implicit scoping crammed into one line, relying on memory and active searching to find the boundaries and then follow the order of events back "to the top", rather than having them explicitly marked.
- erikpukinskis 5y agoYeah, I think nested ternaries are fine as long as it’s just a list like OP is suggesting… But it breaks peoples brains for some reason so I rarely use them professionally. It’s really not that hard though, the ? and : are just shorthand for “else if” and “then”.
- esperent 5y agoWhile I do use this style occasionally, the previous commenter's point still stands that as value1, value2, fallback become longer than a couple of characters it does become very hard to read. It's also something that can start out fine but as the code grows more complex over time it can spiral into unreadability.