How to loop through array in jQuery?
Here's the quickest way to loop through an array in jQuery using the $.each()
function:
This will print each item's index and its corresponding value to the console.
Additionally, modern JavaScript methods such as Array.prototype.forEach
or the ES2015 for...of
loop could be a good option if you prefer cleaner syntax and more readability.
A quick tour of JavaScript alternatives
If you're coding in a current modern JavaScript environment, and are not necessarily bound to jQuery, consider these alternatives that are expressive and preferred.
The forEach
method
Here, we've gone declarative and avoided those pesky counter initializations and bounds issues of the traditional for
loops.
The ES6 for...of
loop
Welcome to ES6! The clean syntax and the power of block-scoped variables make code easier to read and maintain.
Why not for...in
loop?
The for...in
loop can be a bit of a troublemaker. It's meant primarily for iterating object properties.
If you're an eternal optimist who believes it can loop through arrays too, remember, it will return string keys (indices) and might give you inherited properties as a bonus!
And yes, you might consider using hasOwnProperty
to filter the unwanted properties, if you choose to live life on the edge:
Quick tips for better performance
Here, we'll discuss optimizations for your looping methods. 'cause who doesn't like a turbo boost, right?
Store the length
In a traditional for
loop, consider storing array's length in a variable:
Congrats! You've just saved JavaScript from having to calculate the length on every iteration.
Know your strings
Going to handle string data? Pre-split it into arrays using .split()
:
Deep dive into $.each()
Understanding callback arguments
The callback function used with $.each()
enjoys company—it expects two arguments: the index (position in array) and the value (element):
Befriend the this
Inside the callback, this
refers to the current array element:
Was this article helpful?