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

Community
  • 1
  • 1
donald
  • 23,587
  • 42
  • 142
  • 223

1 Answers1

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.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
  • Or, alternatively, use something like jQuery's [$.each](http://api.jquery.com/jQuery.each/), which will break if you return `false`. – Trevor Burnham Oct 17 '11 at 04:00
  • 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. –  Oct 17 '11 at 04:37
  • Isaac, compare forEach with, eg, map, with the loop body as a closure. – Charlie Martin Oct 17 '11 at 06:37
  • Sure, you *can* create side effects with `map` by modifying your enclosed variables, but that's using it non-functionally. –  Oct 17 '11 at 20:04
  • And you can do things in a forEach that don't have side-effects. – Charlie Martin Oct 18 '11 at 15:13