5 ms·
I guess what you find readable also depends on where you're coming from. When I first saw that foo() && bar() line in the OP, I knew what it meant immediately.
by iamwil 16y ago
I guess what you find readable also depends on where you're coming from. When I first saw that foo() && bar() line in the OP, I knew what it meant immediately. It's because I use it myself, and I've seen raganwald's andand operator and heard of Haskell's Maybe monad.
I've used it for so long that it's come to mean "if the first exists, then do the second", and not just "this expression is true if both are true", and I don't really confuse the two.
- erlanger 16y agoYou'd exaggerate the problem at hand too if you were pushing some strange variant of the language criticized. Any programmer experienced with C-style languages recognizes logical constructs with && and || immediately. If function (x) { x = x || someDefaultValue; for setting non-falsy default argument values isn't a JavaScript idiom, I don't know what is.
- aaronblohowiak 16y agoi much prefer x || (x = someDefaultValue) because it doesn't require backtracking. by that i mean, when i read x = x || somedefaultValue, i am thinking x = "okay, we are in an assignment) and then i see x || and then i have to adjust and think "oh, well, this is a conditional so now i have to think about that situation." with x || (x = someDefaultValue), what you read is how it is evaluated. if x is true, the rhs is never evaluated. with the above, the assignment happens either way.
- TrevorBurnham 16y agoBut that's not the code I was criticizing. In fact, it's precisely because that's the idiom I associate with boolean operators in JavaScript that the code snippet I posted struck me as unintuitive. As to "pushing some strange variant": Guilty as charged. Have you tried CoffeeScript? It's fantastic. The code you gave above would be written as (x) -> x ||= someDefaultValue
- erlanger 16y ago> Have you tried CoffeeScript? Nope. I'm apprehensive about adding another layer to the development process when I know JS very well and don't find it at all limiting. So I'm probably not part of your target audience.
- TrevorBurnham 16y agoI was skeptical at first too, and I wouldn't recommend it to anyone who doesn't already have a pretty good understanding of JavaScript. But I'd urge you to try it for a week or so. It's not a layer of abstraction like GWT; it's just a nice, succinct syntax that compiles statement-by-statement to JavaScript.
- jwecker 16y agoSimilarly- it's idiomatic in bash scripting and very common (execute the first command and the second if the first one succeeds). I think it's funny that he naively assumes that because it's unfamiliar to him it must be the less-clear way to do it.