Coffeescript ||= analogue?

I personally use or= instead of ?= mainly because that's what I call ||= (or-equal) when I use it in Ruby.

robot.brain.data.contacts or= {}

The difference being that or= short-circuits when robot.brain.data.contacts is not null, whereas ?= tests for null and only sets robot.brain.data.contacts to {} if not null.

See the compiled difference.

As mentioned in another post, neither method checks for the existence of robot, robot.brain or robot.brain.data, but neither does the Ruby equivalent.

Edit:

Also, in CoffeeScript or= and ||= compile to the same JS.


You can use ?= for conditional assignment:

speed ?= 75

The ? is the "Existential Operator" in CoffeeScript, so it will test for existence (not truthiness):

if (typeof speed === "undefined" || speed === null) speed = 75;

The resulting JS is a bit different in your case, though, because you are testing an object property, not just a variable, so robot.brain.data.contacts ?= {} results in the following:

var _base, _ref;
if ((_ref = (_base = robot.brain.data).contacts) != null) {
  _ref;
} else {
  _base.contacts = {};
};

More info: http://jashkenas.github.com/coffee-script/


It's called the existential operator in Coffeescript and is ?=, http://coffeescript.org/. Quoting below:

The Existential Operator

It's a little difficult to check for the existence of a variable in JavaScript. if (variable) comes close, but fails for zero, the empty string, and false. CoffeeScript's existential operator ? returns true unless a variable is null or undefined, which makes it analogous to Ruby's nil?

It can also be used for safer conditional assignment than ||= provides, for cases where you may be handling numbers or strings.


?= will assign a variable if it's null or undefined.

Use it like speed ?= 25