Skip to content Skip to sidebar Skip to footer

Understanding Return Function(x) From Outer Function(array)

I am learning JavaScript and got a bit confused with the following exercise. I did had to create a filter that would accept another functions as a sorting method. The thing that I

Solution 1:

I'll take this line as example:

filter(arr, inArray([1, 2, 10])) );

inArray is called with arr = [1, 2, 10].

It returns the following (anonymous) function, for that particular arr:

function (x) {
    return arr.indexOf(x) != -1;
}

So the original line now can be pictured as:

filter(arr, function (x) {
    return [1, 2, 10].indexOf(x) != -1;
});

Now filter is called with func set to that anonymous function. The following code calls that function:

if (func(value)) {
        result.push(value);
    }

So when this func is called, this really means the above anonymous function is called, and the parameter x gets set to value at the moment of the call. It is just like with any other function call, the parameters of the function get the values of the arguments in the actual call.

Solution 2:

Your filter function accepts the array to filter, and a function that does the filtering. In this part:

for (var i = 0; i < arr.length; i++) {

    var value = arr[i];
    if (func(value)) { //here, you invoke the function on the array's values
        result.push(value);
    }
}

So if, for instance, we look at the inBetween(3, 6) function, which is this:

returnfunction(x) {
    return3 <= x && x <= 6;
}

(If you don't understand this part, read some more about Closures)

So now that function is simply a function that accepts a value and returns true/false on whether or not it's between 3 & 6.

You eventually get an invocation on each of the array's values (1, 2, 3 ... 7) with the above function.

Same goes for all other functions you listed.

Solution 3:

In this line:

filter(arr, inBetween(3, 6))

You are not "passing a function", but passing the result from a function call. The result is another (anonymous/unnamed) function.

From this line:

function filter(arr, func) {

We know name the function passed as an argument to filter is named func, then:

if (func(value)) {

executes this function.

In JavaScript, a function is just an object like other objects. To differentiate "function object reference" from "function calls", you can look for ().

inBetween is a function object reference, inBetween(x, y) means calling this function.

Anonymous functions can be defined, assigned to a variable, and passed as an argument as well. It may be executed instantly after definition as well:

function() {
  alert("called!");
}();

This may look exotic to people new to JavaScript though.

Post a Comment for "Understanding Return Function(x) From Outer Function(array)"