JavaScript function arguments for filter function

filter, javascript

Solution

`.filter` (`Array.prototype.filter`) calls the supplied function with 3 arguments:

function(element, index, array) {
    ...

- `element` is the particular array element for the call.

- `index` is the current index of the element

- `array` is the array being filtered.

You can use any or all of the arguments.

In your case, `i` refers to the `element` and is used in the body of your function:

function(i){
    return (i > 2);
}

In other words, "filter elements where `element` is greater than 2".

Problem

``` numbers = [1,2,3,4,5,4,3,2,1]; var filterResult = numbers.filter(function(i){ return (i > 2); }); ``` I don't understand how this works. if I omit the i as a function argument it breaks the function but the i isn't tied to anything so why does it need to be there?

Original source