Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hard time understanding javascript example

Tags:

javascript

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);
like image 699
Yapartase Avatar asked Aug 30 '16 14:08

Yapartase


1 Answers

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.

like image 125
vp_arth Avatar answered Nov 05 '22 11:11

vp_arth