Coffeescript ||= analogue?
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/
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.
?=
will assign a variable if it's null
or undefined
.
Use it like speed ?= 25