简体   繁体   中英

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?

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 ? ""

I found this works for me:

c.urls.voice ? ""

which will compiles into:

var _ref;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM