How to use forEach method in Javascript

0 min read 62 words

Arrays come with a useful forEach function that allows you to loop through the array.

var colors = ['red', 'blue', 'green'];

colors.forEach(function(color) {
  console.log(color);
});

// red
// blue
// green

You can also get the index in each loop as follows:

const colors = ['red', 'blue', 'green'];

colors.forEach((item, index)=>{
  console.log(index, item)
});

// 0 'red'
// 1 'blue'
// 2 'green'
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags