How to skip to next iteration in jQuery.each() util ?

jQuery each() function allows us to loop through different datasets such as arrays or objects. jQuery.each() is one of the most used functions in jQuery.

Syntax:

$(selector).each(function(index, element))
$.each(function(index))

$.each() is essentially a drop-in replacement of a traditional for or for..in loop.

Example 1: This example skipping step 4 to next iteration i.e. Step 5.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>jQuery.each() method</title>
    <script src=
    </script>
</head>
  
<body>
    <script>
        var arr = ["Step1", "Step2", 
            "Step3", "Step4", "Step5"];
              
        $.each(arr, function (i) {
            if (arr[i] === "Step4") {
                return;
            }
            document.write(arr[i] + ' ');
        });
    </script>
</body>
  
</html>

chevron_right


Output:



Step1 Step2 Step3 Step5

Explanation: In the above code, you can see that when the iteration comes at “i=4” then the “if” condition becomes “true” that returns a non-false value. So it skips the next iteration i.e. Step 4.

Example 2:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>jQuery.each() method</title>
    <script src=
    </script>
</head>
  
<body>
    <script>
        var arr = [1, 2, 3, 4, 5];
        $.each(arr, function (i) {
            if (arr[i] === 3) {
                return true;
            }
            document.write(arr[i] + ' ');
        });
    </script>
</body>
  
</html>

chevron_right


Output:

1 2 4 5

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.