EN
JavaScript - loop through array
0
points
In this article, we would like to show you how to loop through an array in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const letters = ['A', 'B', 'C'];
// using simple for loop
for (let i = 0; i < letters.length; i++) {
console.log(letters[i]);
}
or
// ONLINE-RUNNER:browser;
const letters = ['A', 'B', 'C'];
// arrayName.forEach(function);
letters.forEach(x => console.log(x));
1. Practical example using Array.prototype.forEach
In this example, we use forEach()
method to iterate the letters
array. We pass two arguments to the arrow function inside forEach() and display them in the console.
Runnable example:
// ONLINE-RUNNER:browser;
const letters = ['A', 'B', 'C'];
letters.forEach((letter, index) => {
console.log(letter, index);
});
2. Using Array.map()
In this example, we use Array.map()
method to loop through the letters
array and execute a function passed to map()
method on each element.
Single parameter:
// ONLINE-RUNNER:browser;
const letters = ['A', 'B', 'C'];
const result = letters.map(letter => {
console.log(letter);
return letter;
});
Multiple parameters:
// ONLINE-RUNNER:browser;
const letters = ['A', 'B', 'C'];
const result = letters.map((letter, index) => {
console.log(letter, index);
return letter + '-' + index;
})
3. Using ES6 for...of
statement
In this example, we use a simple for...of statement to iterate the letters
array.
// ONLINE-RUNNER:browser;
const letters = ['A', 'B', 'C'];
for (const letter of letters) {
console.log(letter);
}