Languages
[Edit]
EN

JavaScript - loop through array

0 points
Created by:
Welsh
772

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);
}

References

Alternative titles

  1. JavaScript - iterate array
  2. JavaScript - array iteration
  3. JavaScript - iterate array forward
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join