When reading the Coffeescript documentation, I was confused by the scant documentation on existential operators. The documentation states
It (
?=
) can also be used for safer conditional assignment than||=
provides, for cases where you may be handling numbers or strings.
What is the difference between the ?=
and ||=
operator and when should one be used versus the other?
CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.
The second problem I've often heard associated with CoffeeScript is speed; i.e. the code produced by the CoffeeScript compiler would run slower than its equivalent written in pure JavaScript. In practice though, it turns out this isn't a problem either.
?
and ||
check entirely different (but overlapping) conditions.
The ||
operator works exactly the same way as it does in JavaScript so things like 0
and ''
are falsey as far as ||
is concerned; ||
checks truthiness in the JavaScript sense.
The ?
operator is converted to == null
in the JavaScript so a ? b
is only b
when a
is null
or undefined
; ?
checks definedness in the CoffeeScript sense.
Consider these:
for v in [false, 0, '', null, undefined, 6]
do (v) ->
a = v
a ||= 'pancakes'
console.log("#{v} ||= 'pancakes':", a)
for v in [false, 0, '', null, undefined, 6]
do (v) ->
a = v
a ?= 'pancakes'
console.log("#{v} ?= 'pancakes':", a)
The first loop will give you five pancakes and one 6
, the second loop will give you a false
, 0
, ''
, two pancakes, and a 6
.
Demo: http://jsfiddle.net/ambiguous/PdLDe/1/
So if you only want JavaScript-style behavior (i.e. 0
, false
, and ''
are to be ignored) then you probably want ||=
. If you only want to skip over null
and undefined
then you want ?=
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With