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.