Yasser
Yasser

Reputation: 1808

Short-circuiting in coffee/javascript

This coffeescript:

if  typeof(groups) is undefined or groups.length == 0

gets compiled into the following javascript:

if (typeof groups === void 0 || groups.length === 0)

Basically i want to check if the groups array is null or empty and hoping that if the first condition is true, the second condition will not be checked (short-circuiting). However Chrome throws the following error:

Uncaught type error: Cannot read property length of undefined

Any insights on why it wouldnt short-circuit?

Upvotes: 2

Views: 785

Answers (3)

Aaron Dufour
Aaron Dufour

Reputation: 17535

CoffeeScript has an operator that takes care of this case for you. If you use:

unless groups?.length > 0

it will form what you're looking for, taking care of the undefined/null cases and only trying groups.length if groups is defined. This has the advantage of being easily chained:

if foo?.bar?.length > 0

Upvotes: 3

epidemian
epidemian

Reputation: 19229

If groups is a local variable, you can ask:

if not groups or groups.length is 0
  ...

If it's a global variable that may not be defined (i.e. accessing groups will throw a "not defined" error), you can use the existential operator ?:

if not groups? or groups.length is 0
  ...

Finally, as you're asking for the length property in the second condition, you can take advantage of the fact that 0 is falsy:

if not groups?.length
  ...

And this last expression won't care if the groups variable is defined or not; it'll work on both cases =D

Upvotes: 0

James Allardice
James Allardice

Reputation: 166021

Because the first condition will never be true. void 0 will evaluate to the value undefined (not the string "undefined"), but typeof returns the string "undefined".

The JavaScript should read:

if (typeof groups === "undefined" || groups.length === 0)

Or:

if (groups === void 0 || groups.length === 0)

To fix your CoffeeScript, you need to check for the string "undefined":

if typeof groups is "undefined" or groups.length == 0

Upvotes: 5

Related Questions