Yapartase Yapartase - 1 year ago 67
Javascript Question

Hard time understanding javascript example

I am currently following a javascript course and am having issues understanding what is happening behind the scenes in javascript in one of the examples (see code below).

I understand most of the code and understand why the output logged is -> [false, true, true]. However there is one part which is driving me nuts (I pointed an arrow to it in the code at the bottom):

my confusion revolves around the parameter


what journey does the parameter
take from the moment it gets passed with
var arr5 = mapForEach(arr1, checkPastLimitSimplified(1));

I understand that when
is invoked an execution context is created for this function in which the parameter 1 is in the variable environment.

But now what happens?
The function inside the
function is not executed yet but just returned. What does it look like when it is returned? at what point do the
variables receive the parameter

I understand that
.bind(this, limiter);
creates a copy of the function. Is its
variable already a 1 before it gets returned?

function mapForEach(arr, fn) {

var newArr = [];
for (var i = 0; i < arr.length; i++) {

return newArr;

var arr1 = [1, 2, 3];

var checkPastLimitSimplified = function(limiter) { // < ----CONFUSED
return function(limiter, item) {
return item > limiter;
}.bind(this, limiter);

var arr5 = mapForEach(arr1, checkPastLimitSimplified(1));

Answer Source

Lets rename variable to see relations:

var checkPastLimitSimplified = function(outer_limiter) {
  return function(limiter, item) {
    return item > limiter;
  }.bind(this, outer_limiter); 

bind modifies function signature to be just function(item) before return.
When client code will call checkPastLimitSimplified(1)(item), limiter will substitute from binded context.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download