Functional Programming - Stuck

Hey guys, I am following along to a JS video on udemy and can NOT get my head around this code.

The first half I get, but the bottom items in bold I can not get it together.

The output is listed next to it and is valid code.

Can anyone explain the bottom 2 items and ’ checkPastLimit.bind(this,2)’ to me?

I can’t see the flow of how this moves through the code.

//

var arr1 = [1,2,3,4,5,6,7,8,9,10];

//

function mapForEach(arr, fn) {
    
    var newArr = [];
    for( i = 0; i < arr.length; i++) {
        newArr.push(
        fn(arr[i])
        )
    };
    return newArr;
}

//

var arr2 = mapForEach(arr1, function(item) {
    return item * 2
});

//

console.log(arr2);   // output: (10) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

//

var checkPastLimit = function(limit, item) {
    return item > limit;
    }

//
 
var arr4 = mapForEach(arr1, checkPastLimit.bind(this,2));
       console.log(arr4);       // output: (10) [false, false, true, true, true, true, true, true, true, true]

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

checkPastLimit returns a boolean, true if item is greater than limit, and false if it isn’t. mapForEach takes an array and a function with which to modify the array.

bind is a function method that returns a new function with this bound to the first parameter. Anything passed after that is a function parameter. We don’t really need to worry about passing this, just know that bind is storing the first parameter of checkPastLimit.

Let’s break out the code a bit more.

var checkPastTwo = checkPastLimit.bind(this, 2);

checkPastTwo(2); // false - same as calling checkPastLimit(2, 2);
checkPastTwo(5); // true - same as calling checkPastLimit(2, 5);

Using bind like this is a technique called partial completion and it’s common in functional programming.

Does this help?

1 Like

Hey this helps a lot, thank you very much!