469

I'm trying to iterate through an array of elements. jQuery's documentation says:

jquery.Each() documentation

Returning non-false is the same as a continue statement in a for loop, it will skip immediately to the next iteration.

I've tried calling 'return non-false;' and 'non-false;' (sans return) neither of which skip to the next iteration. Instead, they break the loop. What am i missing?

1
  • 9
    In their infinite wisdom, the bods at jQuery have now removed this note from the documentation - or at least, it's not in the page for each(). So I'm very glad to see this question can still be found here on SO, and by extension on Google, as this is one of those simple things I always forget :) Commented Aug 1, 2015 at 1:16

5 Answers 5

828

What they mean by non-false is:

return true;

So this code:

var arr = ["one", "two", "three", "four", "five"];
$.each(arr, function(i) {
  if (arr[i] == 'three') {
    return true;
  }
  console.log(arr[i]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

will log one, two, four, five.

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

4 Comments

To exit only current iteration it's enough just to return 'return'. And to exit all iterations forward return false.
Its worth saying that this works because you are within a function when this code is executed.
when i do return (arr[i] === 'three'); why it is not working??
To me, non-false mean, you can return anything except return false;
62

By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return true, 1, 'non-false', or whatever else you can think up.

3 Comments

why not just for explicities sake " return 'continue';"
what about continue;? that worked in a variation of C sharp I worked with so I'm only guessing it'd have a similar effect in JS
@Brandito It isn't running like a normal loop - it is calling a function recursively, so in order for the loop to continue you need to end the processing inside the function.
5

The loop only breaks if you return literally false. Ex:

// this is how jquery calls your function
// notice hard comparison (===) against false
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
   break;
}

This means you can return anything else, including undefined, which is what you return if you return nothing, so you can simply use an empty return statement:

$.each(collection, function (index, item) {
   if (!someTestCondition)
      return; // go to next iteration

   // otherwise do something
});

It's possible this might vary by version; this is applicable for jquery 1.12.4. But really, when you exit out the bottom of the function, you are also returning nothing, and that's why the loop continues, so I would expect that there is no possibility whatsoever that returning nothing could not continue the loop. Unless they want to force everyone to start returning something to keep the loop going, returning nothing has to be a way to keep it going.

Comments

5

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

1 Comment

Links are broken... Btw, 0 is also a falsy value and the negation of it is truthy (and vice-versa to any other number, e.g. !-42 === false).
4

Dont forget that you can sometimes just fall off the end of the block to get to the next iteration:

$(".row").each( function() {
    if ( ! leaveTheLoop ) {
        ... do stuff here ...
    }
});

Rather than actually returning like this:

$(".row").each( function() {
    if ( leaveTheLoop ) 
        return; //go to next iteration in .each()
    ... do stuff here ...
});

3 Comments

I don't mean to be rude but this is painfully horrible design. I mean... I've done it, in my 2 first years of college, when I didn't know better (even then I didn't like it), but it's not something that should be adviced...
@DanielParejoMuñoz, I hear you, but we disagree. The choice to not have a return statement may not be something you like. But I would submit that its a like/dislike thing rather than a good/bad thing. Neither has clear advantages objectively.
this has the disadvantage of increasing nesting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.