Yapartase
Yapartase

Reputation: 85

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 1:

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

I understand that when checkPastLimitSimplified(1) 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 checkPastLimitSimplified function is not executed yet but just returned. What does it look like when it is returned? at what point do the limiter variables receive the parameter 1?

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

function mapForEach(arr, fn) {

  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    newArr.push(
      fn(arr[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));
console.log(arr5);

Upvotes: 6

Views: 195

Answers (2)

Eduardo Resende
Eduardo Resende

Reputation: 33

another way to make it more understandable is putting the inner function outside:

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

var checkPastLimitSimplified = function(outer_limiter) {
    return checkPastLimit.bind(this, outer_limiter); 
};

The result will be a copy of the first function with the first parameter (limiter) already defined.

This new function will need only the second param (item).

But there is no execution of the function code (the comparison with the limit) on this stage.

Upvotes: 0

vp_arth
vp_arth

Reputation: 14982

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.

Upvotes: 4

Related Questions