Languages
[Edit]
EN

JavaScript - loop through array

0 points
Created by:
Romany-Welsh
382

In this article, we would like to show you how to loop through 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));

Multiple parameters:

// ONLINE-RUNNER:browser;

const letters = ['A', 'B', 'C'];

const result = letters.map((letter, index) => {
    console.log(letter, index);
})

3. Using ES6 for...of statement

In this example, we use 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

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