james
james

Reputation: 4049

How are the parameters passed in this function?

Doing a text book exercise where:

let arr = [1, 2, 3, 4, 5, 6, 7];

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

alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6

The textbook also states that the filter syntax to be:

let results = arr.filter(function(item, index, array) {
  // should return true if the item passes the filter
});

So I'm not completely understanding how the inBetween(a,b) function works... like in this line:

arr.filter(inBetween(3,6))

It seems to me like a is the item parameter, b is in the index parameter, but obviously that's not how it's working... Can someone break down this syntax and why it's working?

Upvotes: 1

Views: 49

Answers (2)

J Livengood
J Livengood

Reputation: 2738

So the filter method accepts a function that should return true or false, whether to keep the item or not.

In this example, instead of writing that function inside the filter, it's written outside and passed in. However you can still think about it like this:

let results = arr.filter(function(item, index, array) {
    return item >= 3 && item <= 6;
});

The reason you would define inBetween outside the filter is so you can pass in values instead of hard coding them into the filter like above.

When you call inBetween(3,6) returned is :

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

Like above that's then put into the filter (just without the index/array parameter since they are not needed:

let results = arr.filter(function(x) {
    return x >= 3 && x <= 6;
});

Upvotes: 2

guest271314
guest271314

Reputation: 1

a and b, 3, 6 are defined in the scope of inBetween and referenced within the returned anonymous function which is the callback of .filter(), as indicated by 4castle, x is item at the callback function

Upvotes: 0

Related Questions