How To Loop Through An Array In JavaScript

In this tutorial, you’ll be going to learn how to loop through an array in javascript. The easiest way to use for loop to loop through an array in javascript which can iterate javascript array step by step.

Javascript array is a collection of different type of values so looping an array is a process of iterating an array to get its value.

But Still, there are multiple ways you can iterate a javascript array. Which you’ll be going to learn in this post so stick to the end.

Javascript array can be an array of strings, an array of numbers, an array of objects and maybe a mixture of it. But it’s value having the same processor. So let’s start the post step by step. In javascript, you can create an array by declaring an array literal to a variable.

You can also check :

  1. Phone Number Validation in HTML5
  2. Convert PHP array to JavaScript array
  3. How To Get Multiple Elements By Id Using Javascript
  4. Remove duplicates from javascript array
JavaScript: Loop Through An Array
JavaScript: Loop Through An Array

So let’s see how actually array looks like.

// declare an array
let array = [1, "codekila", 2, "loop", 3, "iterate"]

How To Loop Through An Array In JavaScript

Table of Content:

  • Using for loop
  • Use While loop
  • forEach in ES5
  • map in ES5
  • filter in ES5
  • reduce in ES5
  • Using for…of
  • Jquery.each method
  • lodash _.forEach method
  • underscore.js .each method

So I told you there are so many ways you can loop through an array. Some of them I have mentioned which we will be going to discuss now.

Loop Through An Array Using for loop

Javascript for loop is a traditional approach to iterate through an array. Javascript array starts from zero indexes so array first element at zeroth index and last index of an array is equal to array length minus one.

Javascript for loop syntax
for(initialization, condition, looping statement){
     // your work goes here
}

So let’s move on to a code section. First, we create an array in javascript then you’ll loop through it.


// declare or create an array
let array = [1, "codekila", 2, "loop", 3, "iterate"]

// javacript for loop
for(let i = 0; i < array.length; i++){
      // iterate through an array using for loop
      console.log(i+ " elemtent is "+array[i])
}

/* 
result of console =>
       0 elemtent is 1
       1 elemtent is codekila
       2 elemtent is 2
       3 elemtent is loop
       4 elemtent is 3
       5 elemtent is iterate
*/

In the above javascript array example, you will see how to iterate through an array using for loop. We have access to the index of an array element and also the value. for loop runs until it satisfies the condition.

Loop Through An Array Using while loop

The javascript while loop is also another good approach to iterate an array. In while loop, you just need to define a condition until loop runs which are obviously equal to array length.

while(condition){
 // your code goes here
}

So let’s iterate an array using while loop. Now move on to the code section.


// create an array
let array = [1, "codekila", 2, "loop", 3, "iterate"]

// declare a variable
let i = 0;
// javascript for loop
while(i < array.length){
      // iterate through an array using while loop
      console.log(i+ " elemtent is "+array[i])
      i++; // increment a value
}

/* 
result of console =>
       0 elemtent is 1
       1 elemtent is codekila
       2 elemtent is 2
       3 elemtent is loop
       4 elemtent is 3
       5 elemtent is iterate
*/

While loop iterates through an array until it satisfies the condition. Which in our case is let i = 0 variable which increments in each iteration until it is less than the length of an array.

Iterate An Array Using forEach ES5

Javascript forEach introduce in ES5 which is an Array method to loop through an array. forEach through a callback in each iteration. forEach array callback contains three-parameters which are an element, current_index, and current_array.

But the second and third parameter is an optional parameter. Let’s see an Array.forEach method in action.

Array.forEach(function(element, current_index, current_array){
   // your code goes here
})

Now move on to a code section that how to iterate through an array using forEach.


// declare an array
let array = [1, "codekila", 2, "loop", 3, "iterate"]

// javascript forEach in ES5
array.forEach(function(elem, index, array){

      // iterate through an array using forEach loop
      console.log(index+ " elemtent is "+elem)

})

/* 
result of console =>
       0 elemtent is 1
       1 elemtent is codekila
       2 elemtent is 2
       3 elemtent is loop
       4 elemtent is 3
       5 elemtent is iterate
*/

Not only an array but an array of object an also loop through using the above method. Using forEach we do not need to declare a variable or increment a variable to get the next index of an array.

Looping an Array Using Array.map() method

Array.map() is used to iterate an array and modify it based on the condition. Array.map() method introduced in an ES5 which is an ECMA Script.

Let’s see how exactly Array.map() method look like in action.

Array.map(function callback(currentValue, currentIndex, mainArray) {
    // Return new array
})

Now we will be looping an array and modify the array. Array.map() method always return a new array.


// declare an array
let array = [1, 2, 3, 4]

// javacript Array.map() in ES5
let new_array = array.map(function(elem, index, array){

      return elem = elem * 2

      // iterate through an array using Array.map 

})
// original array
console.log(array)
// result => [ 1 , 2 , 3 , 4 ]

// new modified array
console.log(new_array)
// result => [ 2 , 4 , 6 , 8 ]

Array manipulation using Array.map() is so easy as you can see our array each element get to multiply by 2 and we get a new array. An array of string can also be modified using Array.prototype.map()

Let’s see an example of a map method with an array of string.


// declare an array
let array = ["codekila", "loop", "iterate", "array"]

// javacript Array.map() in ES5
let new_array = array.map(function(elem, index, array){

      return elem.toUpperCase()

      // iterate through an array using Array.map 

})
// original array
console.log(array)

// new modified array
console.log(new_array)

So any type of array it is map handle everything. Now we can also get particular value from an array of object. Using Array.map method, we can convert an array of object to array.


// declare an array of object
let array = [
          {
            name : "codekila",
            key : "value"
          },
          {
            name : "loop",
            key : "myValue"
          },
          {
            name : "jsArray",
            key : "thisValue"
          }
]

// javacript Array.map() in ES5
let new_array = array.map(function(elem, index, array){

      return elem.name

      // iterate through an array using Array.map 

})

// new modified array
console.log(new_array)
h
// result => [ "codekila" , "loop" , "jsArray" ]

An array of the object can easily convert from array to object using Array.map() method. Our array of an object contains an object which has two key and we convert one javascript object key value to an array.

Iterate Through An Array Using Array.filter() method

Array.filter method is used to filter an array. It iterates an array and gives an array based on the condition. Array.filter method through a callback in each iteration.

Javascipt filter is a array method used to filter an array based on condition and it return a new array.

Array.filter callback also contain three-parameter which are an element, current_index, and current_array.

Array.filter(function(elem, index, arr){ })

Array.filter((elem, index, arr)=>{ })

let’s see an example with primitive values.


// declare an array of object
let array = [12, 21, 16, 10]

// javacript Array.filter() in ES5
let filter_array = array.filter(function(elem, index, array){

      return elem > 15
      // iterate through an array using Array.filter 

})

// new filter array
console.log(filter_array)

In the above example, we iterate an array and filter the array which returns a filtered array.

you will also filter an array of an object using Array.filter() method. Let’s see it in the example.

So until now, we are discussing the function and functionality provided by javascript and some new ECMA Script Array method now we have some javascript library also.

Loop Through An Array Of Object Using Array.filter() Method


// declare an array of object
let array = [
          {
            name : "codekila",
            value : 12
          },
          {
            name : "jsArray",
            value : 21
          },
          {
            name : "loop",
            value : 16
          },
          {
            name : "jsArray",
            value : 10
          }
]

// javacript Array.filter() in ES5
let new_array = array.filter(function(elem, index, array){

      return elem.value > 15
      // iterate through an array using Array.filter 

})

// new modified array
console.log(new_array)

/*
  result =>
       [
          {
            name : "jsArray",
            value : 21
          },
          {
            name : "loop",
            value : 16
          },
      ]
*/

So an array of an object is filter based on value key and it can be a name key also. It depends on the requirement.

Loop Through An Array Using Array.reduce() method

Array.reduce can also iterate through an array and provide either array or value. Array.reduce contain four fields in its callback.

Javascript reduce is a method which reduce array to single value. Reduce have a four argument in it’s callback function.

Array.reduce(function(accumulator, elem, index, arr){ }, initialValue)

Array.reduce((accumulator, elem, index, arr)=>{ }, initialValue)

Reduce method has a very nice argument which is known as an accumulator variable in reduce callback argument.

Let’s take an example of Array.reduce() method.


// declare an array of object
let array = [1, 2, 3, 4]

// javacript Array.reduce() in ES5
let sum_array_values = array.reduce(function(total, elem, index, array){

      return total = total + elem
      // loop through an array using Array.reduce 

},0)

// new value
console.log(sum_array_values)

// result => 10

As you can see we reduce the array to value. Array.reduce() method iterate an array and using reduce we can sum all array values.

Looping an Array Using for…of

for…of is another good approach to loop through an array. for..of is looping throughout the array length.

let’s see it an example.


// declare an array
let array = [1, 2, 3, 4]

// javacript for of 
for(let value of array){

  // loop througn an array an print array value
  console.log("elem ",value);

}

// result => 
/*
 elem 1
 elem 2
 elem 3
 elem 4
*/

As you can see inside for we pass variable with of where variable value contains value on array in each iteration.

Loop Through An Array Using Jquery.each() Method

jquery is a javascript library which is full of cool utility helper function which reduces the time to develop a module. jquery have a $.each method which can iterate through an array.

let’s see jquery.each() method example.


// create an array 
let array = [1, 2, 3, 4]

// jquery each method 
$.each( array, function( index, value ){

  // loop througn an array an print array value
  console.log("element "+value);

})

/*
result =>
 element 1
 element 2
 element 3
 element 4
*/

Loop Through An Array Using lodash _.forEach method

Until now, we are seeing the functionality provided by javascript to loop through an array but their also another nice library which is lodash.

Lodash is a javascript utility library which reduces the time to develop this kind of functionality. Lodash has a function _.forEach which iterate an array.

To implement lodash library, first, we need to include a lodash library in an HTML page using script tag.

<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
</head>

Lodash uses underscore as a reference to apply its functionality. Like you create an array in javascript and looping it using _.forEach.

Just look at an example.


// create an array 
let array = [1, 2, 3, 4]

// lodash forEach method 
_.forEach( array, function( value ){

  // loop througn an array an print array value
  console.log("element "+value);

})

/*
result =>
 element 1
 element 2
 element 3
 element 4
*/

Loop Through An Array Using Underscore.js _.each method

So, Underscore.js is also a javascript utility library like lodash. which reduce the time of creating already known problems like iterate an array

Same as lodash, in order to implement in HTML page we need to put an underscore.js library in the head section of an HTML page.

<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
</head>

let’s see an example with underscore.js like lodash underscore also _ as a reference.


// create an array 
let array = [1, 2, 3, 4]

// underscore.js each method 
_.each( array, function( value ){

  // loop througn an array an print array value
  console.log("element "+value);

})

/*
result =>
 element 1
 element 2
 element 3
 element 4
*/

So their lot of other libraries also in the market which you can use to get the same result. you can also create your own array prototype not a big deal

Conclusion :

As you can see there are many ways you can implement for how to loop through an array in javascript.

We have used only functions and functionality provide by JavaScript only like a for loop, while loop, mapfilterreduce and more.

And we have also used a library like jquery, lodash and underscore to get the same result.

I hope you read the full article and I am very excited to get a comment on this post to get your review.

If you have any question please feel free to ask me in the comment section and also let me know if you have any suggestion is also acceptable. Also, like our Facebook Page.

You can also check :

  1. How to check if an object is empty in javascript
  2. How To Empty An Array In JavaScript
  3. Get Multiple Elements By Id Using Javascript
  4. Remove duplicates from a javascript array

Leave a Reply

Your email address will not be published. Required fields are marked *