Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Conditionally building an array in a loop comprehension can result in 'undefined' array elements #1052

Closed
edoloughlin opened this Issue · 4 comments

2 participants

edoloughlin Timothy Jones
edoloughlin

I'm using a loop comprehension to filter out an element of an array:
participants = for participant in @interview.participants
participant unless participant.email == event.data.email

The assignment line of interest above gets compiled to:
_results.push(participant.email !== event.data.email ? participant : void 0);

So, if the test is negative I end up with an 'undefined' entry in my array instead of just skipping that entry, which makes it difficult to loop over that array subsequently...

Timothy Jones
Collaborator

Use the when guard clause on your loop, that will stop the loop from running on those particular instances.
participants = (p for p in @interview.participants when p.email isnt event.data.email)

edoloughlin

That's an ok workaround, but I do you think the code above is valid code?

Is it reasonable to assume I'd get an empty array (or null) if nothing matches? In that case, I think an array with n 'undefined' elements isn't correct behaviour.

Timothy Jones
Collaborator

Remember that every conditional is really a ternary, and what you've written is actually sugar for:
if participant.email isnt event.data.email then participant
else undefined
That's why it comes out as above - every inside run of the loop has to produce some kind of value, and every conditional has an else clause whether you wrote it in or not. Hence we have the guard if you want to avoid putting in an element at all.

edoloughlin

That's fair enough. I guess I didn't get a sense of this from the docs.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.