There is a code of the function "filter" for filtering the array "arr", according to the results of the execution of the function "func".

function filter(arr, func) { var result = []; for (var i = 0; i < arr.length; i++) { var val = arr[i]; if (func(val)) { result.push(val); } } return result; } function inBetween(a, b) { return function(x) { return x >= a && x <= b; }; } var arr = [1, 2, 3, 4, 5, 6, 7]; alert( filter(arr, inBetween(3, 6)) ); // 3,4,5,6 

Please explain how val=arr[i] is passed to x .

    2 answers 2

    The inBetween function returns a new function with one argument x . The new function closes on two variables a and b , which are arguments inBetween .

    That is, after calling inBetween(3, 6) , we have a new anonymous function that would look like this:

     function(x) { return x >= 3 && x <= 6; } 

    We transfer this new function to filter(/* тут массив */, /* тут новая функция */)

     function filter(arr, func) { var result = []; for (var i = 0; i < arr.length; i++) { var val = arr[i]; if (func(val)) { result.push(val); } /* Здесь надо помнить, что func - сейчас та самая новая функция с одним аргументом х. Так как val у нас равен arr[i], а val мы передаем в качестве аргумента к func, получается, что arr[i] попадает в х */ } return result; } 
    • Thank. That is, the if(func(val)) condition can be interpreted as if the function "func", has the argument "val" and the result of the work func(val) , is a certain value that is different in the logical sense from "false", add to the array " result ", element, with value" val ". - Alexander Korinskiy
    • In a slightly different way: if the result of calling the func function with the val argument is some value other than "false" in a logical sense, add to the "result" array, an element with a value "val" - Vladimirov Alexey

    The inBetween function returns closure (closure) - it is the same anonymous function inside inBetween . In its scope there are parameters a and b entering into it, which allow to check the number x . The filter function itself takes an array as the first argument and a callback function with which the elements of the array are filtered.