Hanfei Sun
Hanfei Sun

Reputation: 47051

Test if a variable is defined, if not, assign it an empty string in Coffeescript?

Here is my coffeescript code:

if c.urls.voice then c.urls.voice else ""

Does anyone have any ideas about whether there is a better way to write this code in Coffeescript?

Upvotes: 0

Views: 434

Answers (2)

Bergi
Bergi

Reputation: 664307

Just use the existential operator to assign to a non-existing variable/property:

c.urls.voice ?= ""

Alternatively, if you don't want to assign it but only access with a default value, use the or (or ||) operator:

… = c.urls.voice or "" // equivalent to your if statement

however I guess you're even here actually looking for the existential operator which specifically checks for null and undefined values, not all falsy ones:

… = c.urls.voice ? ""

Upvotes: 3

Hanfei Sun
Hanfei Sun

Reputation: 47051

I found this works for me:

c.urls.voice ? ""

which will compiles into:

var _ref;

if ((_ref = c.urls.voice) != null) {
  _ref;
} else {
  "";
};

Upvotes: 0

Related Questions