jQuery map Callback Return Value Explained
The jQuery .map() method relies on a callback function
to transform elements within a collection into a new set of values. When
writing a callback for .map(), the expected return value
can be a single transformed value, an array of values, or
null/undefined. Depending on what is returned,
jQuery either appends the value, flattens the array into the final
collection, or removes the element entirely from the resulting set.
Allowed Return Values and Behaviors
The callback function passed to jQuery .map() can return
three types of results:
- A Single Value: Returning any single JavaScript value (such as a string, number, object, or boolean) places that item into the new collection at the corresponding position.
- An Array of Values: If the callback returns an array, jQuery automatically flattens the array. Each item within the returned array becomes an individual element in the resulting collection rather than being stored as a nested array.
nullorundefined: Returningnullorundefinedinstructs jQuery to omit the current item entirely. This allows.map()to act simultaneously as both a mapper and a filter.
Difference Between
$(selector).map() and $.map()
jQuery provides two variants of the .map() method, and
both follow the same return value rules, though their callback
parameters are ordered differently:
- Collection method:
$(selector).map(function(index, domElement))Operates on a jQuery selection. The callback receives theindexfirst and thedomElementsecond. It returns a new jQuery-wrapped collection. - Utility method:
$.map(arrayOrObject, function(elementOrValue, indexOrKey))Operates on plain JavaScript arrays or objects. The callback receives the element or value first and the index or key second. It returns a standard JavaScript array.
Code Example
// Using $(selector).map()
const result = $('li').map(function(index, element) {
const text = $(element).text();
if (text === 'Skip') {
return null; // Omitted from the final result
}
if (text === 'Split') {
return ['Part 1', 'Part 2']; // Flattened into separate items
}
return text.toUpperCase(); // Single transformed value
}).get(); // .get() converts the jQuery object to a native JavaScript arrayContrast with
Native JavaScript Array.prototype.map
Unlike JavaScript's built-in Array.prototype.map(),
which always maintains a 1-to-1 length mapping and keeps
null or undefined in the output, jQuery's
.map() dynamically changes the size of the resulting
collection by flattening returned arrays and dropping null
or undefined values.