12 Days of Posts: Day 2 – Partial application of a function

This day’s post is a continuation of the last post. In the last post we covered that a function can return a function, but we did not cover any use cases. This post will discuss a very useful one.

We have an add function:

function add(x, y){
  return x + y;
}

We can partially apply one of the parameters and return a new function. To reinforce what this means we will look at an example.

function partiallyApply(param, func){
  return function(nextParam){
    return func(nextParam, param);
  }
}

var addOne = partiallyApply(1, add);

The variable addOne takes the add function and partially applies one of the parameters (y is now always 1). When we execute partiallyApply we bind the first parameter and return a new function which allows us to bind the other parameter later. This means we can do this:

addOne(5);
//returns 6
addOne(10);
//returns 11
var addTen = partiallyApply(10, add);
addTen(5);
//returns 15

What good is this? Well we essentially are passing in parameters over two separate points in time. I had a problem where I needed an index for an item in a list and the event object. The issue was that I did not have these two things at the same time. The event object is only created in response to an event. I partially applied the index first which returned a function that would accept the event object. I have the code in the react_components.js file in my Where to eat repository.

The next post will continue the JavaScript theme.


Enjoyed the article?

Then I guarantee that you will find my video series useful and enjoyable. The course focuses on taking someone completely new to Node.js and giving them a great foundation to start building real applications. The course is named The Complete Guide to Node.js.

Feel comfortable with Node.js and want to build web applications? Then you will find my other video series useful. It is named Building Complex Express Sites with Redis and Socket.io

I also have a book! It covers Node.js, Express, Passport, Socket.IO, Redis, RabbitMQ, React, Backbone, Grunt, and Ansible. All in one book! It is called Building Scalable Apps with Redis and Node.js.

Receive tips on Node.js, Python, and more