7

Possible Duplicate:
Javascript Array.forEach HowTo break?

Given that I have a forEach loop, how do I break out of that loop in case X is true?

For example:

user.forEach (x,i) ->

                    if x.status == "available"
                        -- I want to break here - 

Thanks

1

1 Answer 1

12

Basically, don't. forEach is meant to be essentially "functional". You could break it with an exception, but exceptions should be used for "exceptional" conditions, not control flow.

If you mean to break, you don't mean a functional form, you mean an iteration. Use a for loop.

Sign up to request clarification or add additional context in comments.

5 Comments

Or, alternatively, use something like jQuery's $.each, which will break if you return false.
I agree with this, but I'm not sure the word "functional" is right, even in scare quotes; the whole point of forEach is to create side effects.
Isaac, compare forEach with, eg, map, with the loop body as a closure.
Sure, you can create side effects with map by modifying your enclosed variables, but that's using it non-functionally.
And you can do things in a forEach that don't have side-effects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.