JavaScript the Fun Part


functional-programming-javascript

partial-application


The fun part is about to start. In previous posts we learned about

Our last code sample was this, that we convert our binary function to a unary function.

// add is a unary function
function add( a ){
    // sum is a unary function
    return function( b ){
        // capturing a and b by reference
        return a + b;
    }
}

And for testing it, we did this

add( 2 );    // function add()
add( 2 )( 3 );  // 5

partially applying an argument

By now we know that our add function, takes one arguments, then returns another function, and that one also takes one argument. So this style should be obvious to you; two consecutive nested functions.

add( 2 )( 3 );  // 5

In this style we have used all the function immediately to gain the result which is 5. If we do not do this, if we just invoke the first function and store the inner function ( one that is returned) then we partially applied an argument. That is partial application.

Lets try it

// using first function
// returning another function that takes one argument
const add2 = add( 2 );

// we already have "2", now we have added 3
const result = add2( 3 );

console.log( result );      // 5

Conceptually is will be something like this when we call add( 2 )

// replacing a with 2
function add( 2 ){
    // sum is a unary function
    return function( b ){
        // capturing a and b by reference
        return 2 + b;
    }
}

Then we call add2( 3 ) it becomes

// replacing a with 2, and b with 3
function add( 2 ){
    // sum is a unary function
    return function( 3 ){
        // capturing a and b by reference
        return 2 + 3;
    }
}

bind, call, apply

May or may now you have used partial application in your JS code. Here are some examples.

Using bind method.

// fixed this binding
const log = console.log.bind( console );

// partially applying on console.log, two arguments
// it is equivalent to console.log( "hello", "JS" );
const greeting = console.log.bind( null, "hello", "JS" );

Now greeting is a function that has captured two arguments

  1. hello
  2. JS

And if we invoke it we will see "hello JS".

greeting();  // hello JS

What is it good for?

At first everyone things what! What is this style good for? Why do not we directly use the function and do it in this style?

That is because you are not seening the pig picture of this technique. It is not useful when we use it just for one function. It will be very useful when we have more than one, two, or more currying functions.

By having many currying function we will be able to partially apply some of them, and then use the rest of our currying function later on, which give us two things

and we discuss composition in next post.


Update: Tue Nov 05 2019 08:37:33 GMT+0330 (Iran Standard Time)