How do you 'continue' like with for loops when iterating with a closure in javascript

Using underscore.js is there a way to breakout of the each if a certain condition is met?

_.each([1,2,3], function(value) { if (value == 2) { // continue 2 return false; } });

I'm sure returning false did the trick in prototype.js

-------------Problems Reply------------

Looks like you should return breaker, which isn't in scope it seems. So, without modifying _, you can't easily break out of iteration. The === there will ensure that returning {} won't cause the loop to break; you need a reference to breaker, which you don't have.

// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects implementing `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (_.isNumber(obj.length)) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj &&, obj[i], i, obj) === breaker) return;
} else {
for (var key in obj) {
if (, key)) {
if (, obj[key], key, obj) === breaker) return;

I'm not sure if you can actually stop the loop but you could use a boolean to stop the code in the loop from executing:

var keep_going = true;
_.each([1,2,3], function(value) {
if (value == 2) {
// continue 2
keep_going = false;

You can't. As Stefan posted above, if your browser does not support Array.prototype.forEach (which is a long shot these days), you could return breaker -- if you had access to it. But unfortunately, you don't, because breaker is defined as {} in a closure in the underscore.js library.

Unfortunately, the behavior of JavaScript is that two objects are not equal to one another unless they are the exact same object. Therefore, ({}) === ({}) is false -- and so returning {} from your function will not pass an equality check with the internal breaker variable.

So, you can't break out of loops like this without roundabout methods like posted above. And, according to the MDC, there is no way to break the native forEach that is used.

It may very well be that .each does not support skipping.

You can do it the roundabout way:

var skip = false;
_.each([1,2,3], function(value) {
if (true === skip) {
if (value == 2) {
skip = true;
return false;

But I'm sure there is a better function for it.

Category:javascript Views:0 Time:2011-06-02

Related post

  • Continue in nested while loops 2009-07-15

    In this code sample, is there any way to continue on the outer loop from the catch block? while { // outer loop while { // inner loop try { throw; } catch { // how do I continue on the outer loop from here? continue; } } } --------------Solutions----

  • can I "break"/"continue" in a while loop in objective-c? 2011-05-07

    can I "break"/"continue" in a while loop in objective-c? (or are these reserved only for for loops) --------------Solutions------------- Yes of course you can! Give it a try! From Apple's Objective-C docs: Objective-C is defined as a small but powerf

  • C# - foreach loop within while loop - break out of foreach and continue on the while loop right away? 2011-07-15

    while (foo() == true) { foreach (var x in xs) { if (bar(x) == true) { //"break;" out of this foreach //AND "continue;" on the while loop. } } //If I didn't continue, do other stuff. } I'm a bit stuck on how to do this. Update: I fixed the question. I

  • Performance of traditional for loop vs Iterator/foreach in Java 2009-12-10

    Is there any performance testing results available in comparing traditional for loop vs Iterator while traversing a ArrayList,HashMap and other collections? Or simply why should I use Iterator over for loop or vice versa? --------------Solutions-----

  • While using a switch case loop, can i use the for loop for iterating the cases? 2010-04-24

    In PHP, While using a switch case loop, can i use the for loop for iterating the cases? for example switch ..... foreach($xyz as $abc) { CASE:$abc } default; UPDATE I am fetching the value from DB, this value is name of table, by using "case" I want

  • Loop through gridview rows on client-side javascript 2011-01-17

    I have a gridview with a template field of check boxes. I have my rows color coded in BLUE color in the gridview based on a database value on page load. Now I want a button on the page to loop through the gridview and select the the checkbox for the

  • What is the difference between loop and iteration? 2011-03-21

    What kinds of data structure are used to implement loop and iteration? --------------Solutions------------- Loop refers to the code... iteration refers to the process in which the content of loop is executed once.. so 1 iteration refers to 1 time exe

  • Continue on error in loop 2008-11-27

    The loop below is callign a proc that does various 'things' If it should throw an exception it also 'raises' it. I want to catch it and ignore it and allow the loop to continue processing the next value in the array. Thanks WHILE indx IS NOT NULL LOO

  • Can the loop continuation condition in for loop be anything that will eventually return a false/null value? 2009-10-22

    This is out of deitel's c++ book and I'm trying to understand a bit more about why the continuation condition works and how it knows to quit. s1 and s2 are arrays so when s2 tries to assign the '\n' to s1 does it return null? void mystery1( char *s1,

  • continue statement inside for loop and if condition 2011-10-16

    I have following code snippet and the output i am getting is 4. Please explain me if it takes i=2 or 0. I am confused. And How output was 4? int main() { int i=2; for(i=0;i<2;i++) { i=i%3; if(i==2) { i++; continue; } else ++i; } printf("%d",i); }

  • Microsoft Office Single Image 2010 continues to configure, endless loop 2012-06-14

    An Update has gotten onto my computer, Microsoft Office Single Image 2010, since I have automatic updating. I run Windows 7-64 bit and Microsoft Office Professional-32 bit. This Single Image Update tries to install whenever I try to open a .doc file

  • Browser continuously to flicker or loop when accessing Outlook. 2012-07-07

    Original title: Trying to connect to Outlook, seems to go in loop/ When trying to go into my browser seems to go in some sort of loop and continuosly flicker in the adres bar and then on the new tab? --------------Solutions------------- H

  • How to get a wav file to play continuously throughout a PPT loop 2014-05-15

    Hello, I’m sure this is a novice question but I’m having difficulties. What I have is a 151 page PPT that I would like to have back ground music playing throughout the presentation. I have the PPT looped with side 1 has hidden for a pause screen and

  • How do I make a bash script continue part of a loop only if there is no error in the first step of the loop? 2012-03-30

    I currently have a .command file for Mac that contains the following: for f in ~/Desktop/Uploads/*.flv do /usr/local/bin/ffmpeg -i "$f" -vcodec copy -acodec libfaac -ab 128k -ar 48000 -async 1 "${f%.*}".mp4 rmtrash "$f" done How can I tell bash to on

  • "For" loop first iteration 2009-12-18

    Greetings pyc-sires and py-ladies, I would like to inquire if there is an elegant pythonic way of executing some function on the first loop iteration. The only possibility I can think of is: first = True for member in something.get(): if first: root.

  • For loop stops iterating after first item in listbox 2011-11-26

    I have a for loop that I want (for every item in a ListBox) to execute a method. What happening now is the first item is being selected, the method is being executed, but then it doesn't select the second item, it just sits there. Can you help? This

  • PHP double while loop, second loop not iterating more than once 2012-03-16

    so I'm working on a "product listing", and the idea is to have the name of the product and then a drop down list of colours derived from the database. The problem is I can only get the "colours" while loop to iterate the once, I get the first product

  • What's the best way to loop through a set of elements in JavaScript? 2008-10-01

    In the past and with most my current projects I tend to use a for loop like this: var elements = document.getElementsByTagName('div'); for (var i=0; i<elements.length; i++) { doSomething(elements[i]); } I've heard that using a "reverse while" loop

  • Django template for loop - Last iteration 2009-05-07

    I have a basic question, in the Django template language how can you tell if you are at the last loop iteration for a "for loop"? --------------Solutions------------- You would use forloop.last. For example: <ul> {% for item in menu_items %}

Copyright (C), All Rights Reserved.

processed in 0.124 (s). 11 q(s)