There are many ways to iterate an array in javascript. This post shows 6 most popular way of iterating an array in javascript.

Initialize

Consider following is the array we are going to work with in our example.


      var arr = ["apple", "banana", "watermelon", "cherry"];  
    

Method 1 : Using sequential for loop

This is the most well known method for iterating an array in javascript. It is recommended to use for loop if index access order is important in iteration


for(var i = 0; i < arr.length; i++)
{
    console.log(arr[i]);
}
// outputs: apple, banana, watermelon, cherry
    

Method 2 : Using forEach

forEach method executes provided function to iterate over each element in an array.


arr.forEach(function(item, index){
    console.log(item);
});
// outputs: apple, banana, watermelon, cherry
    

Method 3 : Using for…of

for...of is the feature of ES6. Please make sure browser compatibility before using for…of in your code. It will iterate over the values of an array.


for(var item of arr)
{
    console.log(item);
}
// outputs: apple, banana, watermelon, cherry
    

Method 4 : Using map

map callback function iterate through each element of an array and constructs a new array from the result of a callback.


var newArray = arr.map(function(item) {
    console.log(item);
    return item + " fruit"; // Will append " fruit" to each item of arr.
});
// outputs: apple, banana, watermelon, cherry
// newArray variable contains ["apple fruit", "banana fruit", "watermelon fruit", "cherry fruit"]
    

Method 5 : Using filter

filter callback function iterate through each element of an array and constructs a new array which passes a condition of a callback function.


var newArray = arr.filter(function(item) {
    console.log(item);
    return item.length <= 5; // Will return only items which has length of <= 5
});
// outputs: apple, banana, watermelon, cherry
// newArray will contain ["apple"]. 
    

Method 6 : Using for…in statement

for...in iterates over enumerable property of an object. It is a good idea to check that is enumerable property belongs to array’s own property or not ? Otherwise for…in loop will iterate over Array or Object’s Prototype property as well.


// For the explanation purpose assign bestFruit property to Array prototype value.
Array.prototype.bestFruit = "mango";

// Consider below for...in loop WITHOUT arr.hasOwnProperty check.
for(var i in arr)
{
    console.log(arr[i]);
}
// outputs: apple, banana, watermelon, cherry, mango

// Consider below for...in loop WITH arr.hasOwnProperty check.
for(var i in arr)
{
    if(arr.hasOwnProperty(i)) // This is required to avoid getting inherited properties of object or array prototype.
    {
        console.log(arr[i]);
    }
}
// outputs: apple, banana, watermelon, cherry
    

References

For…in documentation on Mozilla Developers Network
for…of documentation on Mozilla Developers Network