3 ms·
It should be pointed out that "var a = a || someDefault;" can bite you when 0, "", or null are valid values for a. The empty string in particular can be surpris
by city41 15y ago
It should be pointed out that "var a = a || someDefault;" can bite you when 0, "", or null are valid values for a. The empty string in particular can be surprising here at times.
- jashkenas 15y agoTotally -- I think that 0 (which is a perfectly valid value for a number to be) bites people doing lazy initialization all the time. For this reason, CoffeeScript provides the existential operator, which asks: does this variable exist? (Is it not null or undefined?) You can use it in the same places you would use "||", as well as some others: # In place of `||` result = answer ? default # Does `object.value` exist? if object.value? # Lazy initialize the speed of the car: car.speed ?= 60 # Give me the value of `length`, only if `object` exists. length = jsonResponse.list.object?.length
- city41 15y agoI still haven't gone over to CoffeeScript. But I must admit Those are some compelling examples. ?= is especially nice (I miss ||= from Ruby)
- gokangaroo 15y agoIn these cases, I would check for the type, so instead of your example, I would say "var a = typeof a !== 'undefined' ? a || someDefault". (Not that that is particularly pretty, it's actually quite ugly.)
- DougBTX 15y agoThat's also a syntax error; I think CoffeeScript wins this round.
- andrewem 15y agoWhen 'false' is a valid value for a you'll also be bitten in the same way.