0

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?

1
  • In that code, voice isn't a variable, it's an Object property. The test is if it's falsey, so will set the value to empty string if its current value is 0, false, null, NaN, and so on, not just undefined. Commented Jun 17, 2015 at 2:38

2 Answers 2

3

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 ? ""
Sign up to request clarification or add additional context in comments.

Comments

0

I found this works for me:

c.urls.voice ? ""

which will compiles into:

var _ref;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.