How does the "||=" operator differ from "?=" in CoffeeScript?

assignment-operator, coffeescript, operators

Solution

The best thing to do would be to look at the resulting JS.

Coffeescript:

apple = 0
walrus = 9
apple ?= walrus // outputs 0
apple ||= walrus // outputs 9

JavaScript:

var apple, walrus;
apple = 0;
walrus = 9;
if (apple == null) apple = walrus;
apple || (apple = walrus);

As you can see, the `?=` explicitly checks is something is `null` or `undefined` in JS. This is very different from `||=` which just relies on whether `apple` is a falsy value.

To expand a bit more `apple ||= walrus` is equivalent in meaning to `apple = apple || walrus`, so any value of apple that is truthy will short-circuit the logic and not change the value of apple.

Problem

What is the difference between these two? From Ruby, I am used to `apple ||= walrus` setting apple equal to walrus only if apple is null. That seems to be the same in JS/CS, though ?= seems to do the same thing. What confuses me is this: ``` apple = 0 walrus = 9 apple ?= walrus // outputs 0 apple ||= walrus // outputs 9 ``` wat

Original source