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
Code language: JavaScript (javascript)

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'
Code language: JavaScript (javascript)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments