How to Use ForEach Method in Javascript

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'