Studying the topic of closure, I encountered the following example, the logic of which is not completely clear.

Function code

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]; console.log(filter(arr, inBetween(3, 6))); 


Question:

Why the call argument func(val) not added as an additional argument inBetween(a, b, val) , but is passed to the value of the x argument of the returned function.

How does the lexical environment look like when I call and pass val to the inBetween function?

PS: I would also be very grateful if you can point out useful sources where you can explore this more deeply. Thank you very much.

    1 answer 1

    not a bad example, although it is rather simple but rather clearly https://habrahabr.ru/post/149526/

     function inBetween(a, b) { //каждая функция имеет свою область видимости, в данной области видимости после вызова сохранятся 2 переменные a,b; // и вернется функция которая принимает параметр x return function(x) { return x >= a && x <= b } } function filter(arr, func) { var result = []; // если в данном месте вывести console.log(func) то увидим следующее //function (x) { // return x >= a && x <= b //} // // для JS это равносильно следующему //function (x) { // var a = 3,b=6 -значения унаследованные из вышестоящей области видимости // // return x >= a && x <= b //} for (var i = 0; i < arr.length; i++) { var val = arr[i]; if (func(val)) { result.push(val); } } return result; } var arr = [1, 2, 3, 4, 5, 6, 7]; document.write(inBetween(3, 6)(5)); //- в данном случае inBetween(3, 6) - вернула функцию куда мы сразу-же передали параметр x = 5