How Returning Null in jQuery .map() Affects Arrays

When working with jQuery's .map() method, returning null inside the callback function completely removes that element from the final resulting array or jQuery collection. Unlike native JavaScript array mapping, jQuery treats null and undefined as signals to omit an item entirely. This behavior allows developers to transform and filter data simultaneously within a single pass, preventing empty or placeholder slots from appearing in the output.

How jQuery Handles null

In both the static $.map(array, callback) utility and the collection-based $(selector).map(callback) method, the callback processes each element sequentially. If the callback returns a value, that value is pushed into the resulting collection. However, if the function returns null (or undefined), jQuery discards the item entirely instead of adding a null entry.

Here is a practical example using $.map():

const numbers = [1, 2, 3, 4, 5];

const evensOnly = $.map(numbers, function(num) {
    if (num % 2 === 0) {
        return num;
    }
    return null; // Odd numbers are removed
});

console.log(evensOnly); 
// Output: [2, 4]

In this case, the odd numbers return null, so they are omitted from the evensOnly array rather than yielding [null, 2, null, 4, null].

Difference from Native JavaScript Array.prototype.map()

The behavior of jQuery's .map() diverges significantly from standard ECMAScript array methods:

  • Vanilla JavaScript (Array.prototype.map): Preserves array length. Returning null explicitly assigns null to that index.
  • jQuery ($.map and $(selector).map): Automatically flattens arrays and eliminates null or undefined values, altering the length of the resulting collection.

To achieve the equivalent of jQuery's behavior in standard modern JavaScript, you would need to chain .filter() with .map(), or use .flatMap() returning an empty array [] for unwanted items.

Usage with DOM Elements

When using $(selector).map(), returning null excludes selected DOM elements from the wrapped set.

const textValues = $('input').map(function() {
    const val = $(this).val();
    return val === '' ? null : val;
}).get();

Calling .get() converts the returned jQuery object into a plain JavaScript array. Any input that contained an empty string evaluates to null and is purged from the final textValues array.