Hard to understand javascript example

I am currently following a javascript course and am having trouble understanding what is going on behind the scenes in javascript in one example (see code below).

I understand most of the code and understand why the output is registered β†’ [false, true, true]. However, there is one part that leads me to nuts (I pointed to it with an arrow in the code below):

my confusion revolves around parameter 1 :

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

I understand that by calling checkPastLimitSimplified(1) , an execution context is created for this function, in which parameter 1 is in the environment variable.

But what is happening now? The function inside the checkPastLimitSimplified function has not yet completed, but has just returned. What does it look like when it returns? at what point limiter variables get parameter 1 ?

I understand that .bind(this, limiter); creates a copy of the function. Is its limiter variable already 1 before it is 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); 
+6
source share
2 answers

Lets you rename a variable to see the relationship:

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

bind changes the signature of the function just function(item) before returning.
When the client code calls checkPastLimitSimplified(1)(item) , the limiter will be replaced from the associated context.

+4
source

Another way to make it more understandable is to put an internal function on the 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 already defined (limiter).

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

But at this stage, the execution of the function code (comparison with the limit) is not performed.

0
source

All Articles