Question about nested functions within higher order function

I understand (so I think at least :)) the concept of closure, the local/global scope and how it works.

let x = 5
let y = 10
function example(arg){
  let inner = arg + x //arg + global variable x
  function deep(){
    let deep = inner * y //outer variable (inside the scope/Enviroment where the deep function was defined) + another global variable
    return deep
  } return deep()
}

console.log(example(5)) //100

But I was reading an article about closures (a good one imho, here the link), and I just got puzzled by the way filter can be used:

function inBetween(a, b) {
  return function(x) {
    return x >= a && x <= b;
  };
}

let arr = [1, 2, 3, 4, 5, 6, 7];
console.log( arr.filter(inBetween(3, 6)) ); // 3,4,5,6

I’m having a hard time understanding it. How is it that the anonymous inner function with the x parameter have access to the array filter is working on? With a prototype I can use this:

let array = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11]
Array.prototype.fun = function(argA, argB){
  let cleanArray = []
  for(let i of this){
    argA <= i && i <= argB ? cleanArray.push(i) : false
  } return cleanArray
}
arr.fun(4, 10) //[ 4, 5, 6, 7 ]

How is that x and this seems to work the same way ? (edit, how is that x is like i inside the for/of loop?) There is something about the higher order function filter (or any other higher order function) that I don’t grasp (a sort of a inner, built-in method under the hood) or someone could provide me an example with any function? Thanks for your time!

-------------------->scope starts here
|function inBetween(a, b) {
| return function(x) {
| return x >= a && x <= b;
| };
|}
|
| let arr = [1, 2, 3, 4, 5, 6, 7];
|-----------------3----->6
|console.log( arr.filter(inBetween(3, 6)) ); // 3,4,5,6
|-------------------------------------->3 and 6
arr--->( __filter__)->inBetween---a-> b
arr--->( __filter__)->inBetween---3-> 6
--------------------------------------------------->scope ends here
anything in it scope is locally accesible 

now onto your question
How is it that the anonymous inner function with the x parameter have access to the array filter is working on? because its in the same scope and if u follow the path of arrows i laid out for u u can see that the connections of a and b is the same as the connection points a 3 and 6

1 Like

this returns a function
a function that is like
function (x) {return x >= 3 && <= 6} (as 3 and 6 are the arguments)

you can see it as

let between3and6 = inBetween(3,6) // inBetween returns a function which is stored in the variable

let arr = [1, 2, 3, 4, 5, 6, 7];
console.log( arr.filter(between3and6) ); // here the function is used

1 Like