Multiple ways to loop through an Array in jQuery JavaScript

Multiple ways to loop through an Array in jQuery JavaScript

In jQuery & JavaScript, there are at times when we need to loop through an array of items (number array, string array, etc). There are many ways to do it 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 with the different methods.

The number array is:

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

1. For Loop

In for loop 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++) {

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

2. For In Loop

In this loop I use the in keyword with for.

for (var index in numbers) {

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

4. Do While Statement

The Do While is similar to 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 {
while (i < 5);

5. jQuery Each Loop

jQuery has a popular jQuery Each method to loop any type of items easily with it.

The looping code here will be:

$.each(numbers, function (index, value) {

Demo Download

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.

Share this article -



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