Iterating over an array in JavaScript can be done using various approaches. Here are some common methods with descriptions and complete code examples are give below:
1. For Loop
Using a traditional for
loop to iterate over each element of the array.
const array = [1, 2, 3, 4, 5]; for (let i = 0; i < array.length; i++) { console.log(array[i]); } /* Output: 1 2 3 4 5 */
2. For…of Loop
Using the for...of
loop, which simplifies the syntax for iterating over the elements of an iterable object, such as an array.
const array = [1, 2, 3, 4, 5]; for (const element of array) { console.log(element); } /* Output: 1 2 3 4 5 */
3. forEach() Method
The forEach()
method is a higher-order function that takes a callback function and applies it to each element of the array.
const array = [1, 2, 3, 4, 5]; array.forEach(element => { console.log(element); }); /* Output: 1 2 3 4 5 */
4. Map() Method
The map()
method creates a new array by applying a function to each element of the existing array.
const array = [1, 2, 3, 4, 5]; const newArray = array.map(element => { return element * 2; }); // Output: [ 2, 4, 6, 8, 10 ] console.log(newArray);
5. Filter() Method
The filter()
method creates a new array containing elements that pass a certain condition.
const array = [1, 2, 3, 4, 5]; const newArray = array.filter(element => { return element % 2 === 0; }); // Output: [ 2, 4 ] console.log(newArray);
6. Reduce() Method
The reduce()
method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
const array = [1, 2, 3, 4, 5]; const sum = array.reduce((accumulator, element) => { return accumulator + element; }, 0); // Output: 15 console.log(sum);
7. While Loop
Using a while
loop to iterate over the array elements based on a condition.
const array = [1, 2, 3, 4, 5]; let i = 0; while (i < array.length) { console.log(array[i]); i++; } /* Output: 1 2 3 4 5 */
8. Do…While Loop
Using a do...while
loop to iterate over the array elements with the condition checked after the loop execution.
const array = [1, 2, 3, 4, 5]; let i = 0; do { console.log(array[i]); i++; } while (i < array.length); /* Output: 1 2 3 4 5 */