Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 583
Chris Avatar asked May 05 '12 18:05

Chris


People also ask

What is CoffeeScript used for?

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.

Should you use CoffeeScript?

CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.


1 Answers

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.

like image 142
loganfsmyth Avatar answered Sep 25 '22 20:09

loganfsmyth