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