Multiple ways to loop through an Array in jQuery & JavaScript

Multiple ways to loop through an Array in jQuery & JavaScript

In jQuery & JavaScript, you need to loop through an array of items (which can be a number array, string array, etc). There are many ways to do it and so in this tutorial we will look on them one by one.

Here I have taken an array of numbers and I will loop through them by using the different looping methods.

The number array is:

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

1. For Loop

In for loop, the looping is done from 0 to the one less than the length of the array. So the loop will execute until the condition is true.

for (var i = 0; i < numbers.length; i++) {
    alert(numbers[i]);
}  

The above code will show us each of these 5 numbers in an alert box.

I used a looping method to extract all the values from an XML file. This is explained at this tutorial – Read XML file with jQuery Load Method and display it in a HTML Table

2. For In Loop

In this loop I use the in keyword with for.

for (var index in numbers) {
    alert(numbers[index]);
} 

Note: I have kept the array after the in keyword. The index variable will contain the current index of the loop, so numbers[index] will provide the current value of the array in the loop.

3. While Loop

The while loop iterates through a block of code as long as a specified condition is true.

var i = 0;
while (i < numbers.length) {
    alert(numbers[i])
    i++;
}

4. Do While Statement

The Do While is similar to the While loop except that this loop will always be executed at least once, even if the condition is false. The reason being the code block is executed before the condition is tested.

var i = 0;
do {
    alert(numbers[i]);
    i++;
}
while (i < 5);

5. jQuery Each Loop

jQuery has a popular jQuery Each method to loop through any type of items.

The looping code here will be:

$.each(numbers, function (index, value) {
    alert(value);
});

Demo & Download links of this tutorial:

Demo Download

Conclusion

There are multiple ways to loop through an array in jQuery or JavaScript and it is up to you to choose any of the above listed methods.

When you want to call a function after every specific interval of seconds then you can use the jQuery setInterval method.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.