Explain Codes LogoExplain Codes Logo

How to loop through array in jQuery?

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Dec 23, 2024
TLDR

Here's the quickest way to loop through an array in jQuery using the $.each() function:

var items = ["A", "B", "C"]; $.each(items, function(index, value) { console.log(index + ": " + value); });

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

items.forEach(function(value, index) { console.log(index + ": " + value); });

Here, we've gone declarative and avoided those pesky counter initializations and bounds issues of the traditional for loops.

The ES6 for...of loop

for (let value of items) { console.log(value); }

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:

for (var index in items) { if (items.hasOwnProperty(index)) { console.log(items[index]); } }

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:

for(var i = 0, length = items.length; i < length; i++) { console.log(items[i]); }

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():

var stringData = "A,B,C"; var items = stringData.split(","); // Now, 'items' is ready to rock the loop floor.

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):

$.each(items, function(index, value) { // 'index' - your friendly neighborhood position in the array // 'value' - the element itself, all geared up for action });

Befriend the this

Inside the callback, this refers to the current array element:

$.each(items, function() { console.log(this); // 'this' is the superhero alias for 'value' });