In JavaScript, you can loop over an array using various methods, such as for loops, forEach(), for…of loops, and map(). Each method has its own advantages and use cases. Here are examples of each method:
The for loop is a basic looping mechanism in JavaScript that iterates through the array elements using their indices.
const array = [1, 2, 3, 4, 5]; for (let i = 0; i < array.length; i++) { console.log(array[i]); }
The forEach() method executes a provided function once for each array element.
const array = [1, 2, 3, 4, 5]; array.forEach(item => { console.log(item); });
The for…of loop is a modern approach that simplifies iteration over iterable objects like arrays.
const array = [1, 2, 3, 4, 5]; for (const item of array) { console.log(item); }
The map() method creates a new array by calling a provided function on each element in the original array.
const array = [1, 2, 3, 4, 5]; const newArray = array.map(item => { return item * 2; }); console.log(newArray); // Output: [2, 4, 6, 8, 10]