Traversing an array in JavaScript means accessing each element in the array, one at a time. It performs operations like – displaying, modifying, or processing the data. JavaScript provides several methods to traverse arrays, ranging from traditional loops to modern, functional approaches.
1. Using the Traditional for Loop
The for
loop is a versatile way to traverse an array. It gives you full control over the iteration process, including access to indices.
let arr = [10, 20, 30, 40, 50];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
2. Using the for…of Loop
The for...of
loop is a modern and cleaner alternative for traversing arrays, directly accessing each element without requiring an index.
let arr = [10, 20, 30, 40, 50];
for (let item of arr) {
console.log(item);
}
3. Using the for…in Loop
The for...in
loop is used to iterate over the indices (keys) of an array. However, it is not recommended for arrays because it iterates over enumerable properties, which can include unexpected keys if the array is extended.
let arr = [10, 20, 30, 40, 50];
for (let index in arr) {
console.log(arr[index]);
}
4. Using the forEach() Method
The forEach()
method is a modern and concise way to traverse an array. It applies a callback function to each element in the array.
let arr = [10, 20, 30, 40, 50];
arr.forEach((item) => {
console.log(item);
});
Another Example
arr.forEach((item, index) => {
console.log(`Index: ${index}, Value: ${item}`);
});
5. Using the map() Method
The map()
method is primarily used for transforming array elements, but it can also be used for traversal since it iterates through all elements.
let arr = [10, 20, 30, 40, 50];
arr.map((num) => console.log(num));
6. Using the while Loop
A while
loop traverses an array based on a condition. It’s less common for simple array traversal but useful when the number of iterations isn’t fixed.
let arr = [10, 20, 30, 40, 50];
let i = 0;
while (i < arr.length) {
console.log(arr[i]);
i++;
}
7. Using the do…while Loop
A do...while
loop ensures the loop executes at least once, even if the condition is false.
let arr = [10, 20, 30, 40, 50];
let i = 0;
do {
console.log(arr[i]);
i++;
} while (i < arr.length);
8. Using Recursion
Recursion provides a functional approach to traverse arrays by calling a function on each element and the rest of the array.
let arr = [10, 20, 30, 40, 50];
function traverseArray(arr, index = 0) {
if (index >= arr.length)
return;
console.log(arr[index]);
traverseArray(arr, index + 1);
}
traverseArray(arr);
9. Using Lodash Library
The Lodash library provides additional methods for traversing arrays.
let _ = require('lodash');
let arr = [10, 20, 30, 40, 50];
_.forEach(arr, (num) => {
console.log(num);
});