Returning False in jQuery .each() vs .map()

In jQuery, returning false inside an .each() loop immediately stops the loop, functioning as a break statement. Conversely, returning false within a .map() loop does not stop execution; instead, it appends the boolean value false to the resulting array. Understanding this distinction is essential for effectively controlling iteration flow and preventing unexpected data in transformed collections.

How return false Works in jQuery .each()

The .each() method is designed as a generic iterator for looping through arrays, objects, or jQuery collections.

When you return false inside the callback function of .each(), jQuery interprets it as an instruction to break out of the loop entirely. It halts any further iterations. If you want to skip the current iteration and proceed to the next one—acting like a continue statement—you return true (or any non-false value).

$.each([1, 2, 3, 4, 5], function(index, value) {
  if (value === 3) {
    return false; // Breaks the loop completely
  }
  console.log(value); // Outputs: 1, 2
});

How return false Works in jQuery .map()

The .map() method is designed for data transformation. It iterates over a collection, applies a callback function to each item, and builds a new array out of the returned values.

Because .map() expects a returned value to insert into the new collection, returning false does not break the loop. The method continues iterating through every item, treating false as a valid mapped value and pushing it into the final array.

var result = $.map([1, 2, 3, 4, 5], function(value, index) {
  if (value === 3) {
    return false; // Does NOT break; adds `false` to the result
  }
  return value * 2;
});

console.log(result); // Outputs: [2, 4, false, 8, 10]

How to Stop or Filter Items in .map()

Because .map() cannot be halted with return false, you must handle breaking and filtering differently:

  1. Omitting Items: If your goal is to skip an item rather than insert false, return null or undefined. jQuery .map() automatically removes null and undefined entries from the resulting array.
  2. Early Termination: If you must terminate a loop early based on a condition, do not use .map(). Instead, use a standard for loop, Array.prototype.some(), or jQuery .each() to manually push items into an external array until the break condition is met.

Key Differences at a Glance

  • Purpose: .each() is for executing side effects; .map() is for transforming data into a new array.
  • Return Value Impact: In .each(), return false breaks the loop. In .map(), return false preserves the loop and adds false to the output array.
  • Skipping Elements: In .each(), use return true to continue. In .map(), use return null or return undefined to omit an item from the final array.