Convert Array-Like Objects Using jQuery $.makeArray
This article provides a quick guide on converting array-like
objects—such as DOM NodeLists and function arguments—into
true JavaScript arrays using the jQuery $.makeArray()
utility. You will learn the syntax, explore practical code examples, and
understand how this conversion enables the use of native JavaScript
array methods like push(), reverse(), and
slice().
Understanding Array-Like Objects
An array-like object is any JavaScript object that has a
length property and indexed elements (e.g., properties with
keys 0, 1, 2, etc.), but does not
inherit from Array.prototype. Common examples include:
- The
argumentsobject inside non-arrow functions. - DOM collections returned by methods like
document.getElementsByTagName()ordocument.querySelectorAll().
Because these objects are not real arrays, attempting to call methods
such as .pop(), .push(), .map(),
or .reverse() on them results in a
TypeError.
The $.makeArray() Syntax
jQuery provides $.makeArray() (or
jQuery.makeArray()) to convert these structures into true
arrays:
var realArray = $.makeArray(arrayLikeObject);The method accepts a single argument—the array-like object—and returns a new, standard JavaScript array containing the elements of that object.
Example 1: Converting
the arguments Object
Inside standard functions, the arguments object holds
all parameters passed to the function. To manipulate these arguments
with native array methods, convert them using
$.makeArray():
function processItems() {
// Convert the arguments object to a true array
var argsArray = $.makeArray(arguments);
// Native array methods are now available
argsArray.reverse();
return argsArray;
}
console.log(processItems("apple", "banana", "cherry"));
// Output: ["cherry", "banana", "apple"]Example 2: Converting a DOM NodeList
DOM queries like getElementsByTagName return an
HTMLCollection, which lacks array utilities:
// Retrieve a collection of DOM elements
var listItems = document.getElementsByTagName("li");
// Convert the HTMLCollection to an array
var itemsArray = $.makeArray(listItems);
// Now you can safely use Array methods
itemsArray.forEach(function(item) {
item.classList.add("processed");
});Summary of Benefits
Using $.makeArray() provides the following
advantages:
- Full Array Prototype Access: Unlocks native array
functions such as
.filter(),.map(),.reduce(), and.sort(). - Cross-Browser Consistency: Handles legacy browser quirks safely when dealing with host objects.
- Safe Cloning: Creates a shallow copy of the elements, preventing unintended mutations to the original collection.