This site runs best with JavaScript enabled.

Basics of Functional Javascript: Array.forEach

Ian Jones

October 05, 2015

Understanding JavaScript's Array.forEach method is essential to getting a grasp of functional programming in Javascript. The forEach method allows you to iterate over an array just like you could with a for-loop.

const array = ['foo', 'bar', 'baz'];
for(let i = 0; i < array.length(); i += 1){
// => 'foo'
// => 'bar'
// => 'baz'
// The same code written with a forEach
// => 'foo'
// => 'bar'
// => 'baz'

ForEach() takes a callback function to be executed once per item in the array. No more writing for-loops to iterate over an array! Learning forEach() is the first step to learning how to use functional programming in JavaScript because many methods such as .map(), .reduce(), .concatAll(), and .filter() all use .forEach() under the hood. To really understand this look at @jhusain's introduction to functional programming! He takes your through building 5 functions (map, filter, concatAll, reduce, zip) from the group up!

Also, take a look at the documentation for Array.prototype.forEach() on MDN.

Discuss on TwitterEdit post on GitHub

Share article