Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

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

edoloughlin opened this Issue Jan 17, 2011 · 4 comments


None yet
2 participants

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...


zmthy commented Jan 17, 2011

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)

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.


zmthy commented Jan 17, 2011

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.

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