Re:Writing Eloquent JavaScript Without CoffeeScript
by city41 on Friday December 09, 2011 @10:38AM
(#3334046)
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.
[ Parent
| on HN ]
Re:Writing Eloquent JavaScript Without CoffeeScript
by jashkenas on Friday December 09, 2011 @10:47AM
(#3334096)
Totally -- 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
Re:Writing Eloquent JavaScript Without CoffeeScript
by city41 on Friday December 09, 2011 @11:35AM
(#3334326)
I still haven't gone over to CoffeeScript. But I must admit Those are some compelling examples. ?= is especially nice (I miss ||= from Ruby)
Re:Writing Eloquent JavaScript Without CoffeeScript
by gokangaroo on Friday December 09, 2011 @11:18AM
(#3334237)
In 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.)