This post will discuss how to iterate over an array in JavaScript.

1. Using for statement

A for-loop repeats until a specified condition evaluates to false. The JavaScript syntax remains similar to C and Java-style for-loop. You can effectively use it to process values in the array, as shown below:

Download  Run Code

 
You can also use a while statement over a for-loop to iterate over an array:

Download  Run Code

2. Using Array.prototype.forEach() function

The forEach() method executes a specified function for each array element. You can use the callback function to process values in the array.

Download  Run Code

 
In ES6, we have arrow functions that can replace anonymous functions.

Download  Run Code

 
The forEach method has a benefit over the traditional for-loop in that we don’t have to explicitly maintain the indexing information as the callback function is automatically invoked with the index of the current element in its second argument.

Download  Run Code

3. Using for…of statement

The ES6 standard introduced the for…of construct for iterating over an iterable. The for…of statement creates a loop that iterates over the property values. It is different from a for…in loop, which iterates over property names instead of property values.

Download  Run Code

4. Using Array Iterator

The ES6 for…of statement internally uses iterators. To explicitly get an Array Iterator in JavaScript, you can call the values() method on the array.

Download  Run Code

5. Using jQuery

Similar to JavaScript forEach() method, jQuery offers the $.each() method, which can be used to loop through the set of the array elements.

Download Code

6. Using Underscore/Lodash Library

Similarly, you can use the _.forEach method from Underscore or Lodash library, which offers similar behavior. Its alias _.each can also be used.

Download Code

That’s all about iterating over an array in JavaScript.