0

Im confused with how the elem get the value of arr?

function lengGreaterThan(num) {
  function lengGreaterThanNum(elem) {
      return elem.length > num;
  }
  return lengGreaterThanNum;
}

let arr = ['Justin', 'caterpillar', 'openhome'];
console.log(arr.filter(lengGreaterThan(6)));
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
Json Prime
  • 180
  • 1
  • 10
  • 1
    `lengGreaterThan(6)` evaluates to `function lengGreaterThanNum(elem) { return elem.length > 6; }`. This function is passed to `.filter()`, which calls it once for each element of the array, passing that element as first argument. Writing a function that is called by the API rather than yourself takes some wrapping your head around it, but it'll click eventually ;) –  Jul 22 '20 at 09:47
  • Read about closures, [here](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work), [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures), [here](https://eloquentjavascript.net/03_functions.html#h_hOd+yVxaku); ... – ibrahim mahrir Jul 22 '20 at 09:52

1 Answers1

1

That is a really confusing way of writing it, but essentially you are just putting a function that takes one parameter into the filter function.

This here would do the same thing:

console.log(arr.filter((elem) => {
    return elem.length > 6;
}));
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
  • Actually it's not the same, OP's code takes the advantage of the closure, and they can reuse the same function to filter based on the different length, whereas you've hardcoded the length to compare. – Teemu Jul 22 '20 at 09:51
  • Thats not what I meant, the code example is just there to explain to what it evaluates in the end for this specific example. The 6 could still be a variable or something. @Teemu – MauriceNino Jul 22 '20 at 09:54
  • @Teemu OP's code uses two separate concepts, a) closures b) writing functions that are called by API methods. As I read the question, OP mainly struggles with b), not so much a), but I could be wrong –  Jul 22 '20 at 09:55