Higher Order Functions in Javascript: .forEach()

Higher order functions. What a fancy name right? In Javascript, functions are considered “first class citizens” because they can be passed as arguments to other functions, and can also be returned from a function. That’s a lot of functions. The power of functional programming comes into play when we explore some of the Underscore.JS methods. The most popular ones include forEach.(), map.(), filter.(), and reduce.(). These are extremely powerful and useful methods for traversing and manipulating arrays. Out of all of them, reduce is probably the most complicated one – and also the most powerful one. We’ll save that for another day.

Let’s take a look at forEach.

var each = function (collection, callback) {
   if(Array.isArray(collection)){
     for(var i=0; i < collection.length; i++) {
     callback(collection[i]);
   }
 }
 else if(typeof collection === 'object') {
   for(var j = 0, key = Object.keys(collection); i < keys.length; i++) {
   callback(collection[key]);
   }
  }
}

Here is a bare bones implementation of the forEach method. Note that we did not include index as a parameter, though it can be refactored quite easily to include it. We use a forEach when we want a projection function to act upon each element in the array. However, note that forEach does not return an array. If you do not need to directly change the elements in the array, but still want a function to act upon each element in the array, then forEach would be a good choice.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s