Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Existential conditional assignment operators in Coffeescript

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?

like image 451
Andrew Mao Avatar asked Mar 26 '13 23:03

Andrew Mao


People also ask

What is CoffeeScript written in?

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.

Is CoffeeScript slower than JavaScript?

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.


1 Answers

? 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 ?=.

like image 59
mu is too short Avatar answered Oct 10 '22 15:10

mu is too short