Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function arguments for filter function

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?

like image 508
Kevin Avatar asked Jun 27 '12 22:06

Kevin


2 Answers

.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".

like image 90
Hamish Avatar answered Sep 22 '22 23:09

Hamish


i is a reference to the current object in the set when inside that closure. It could be named anything as it is just a variable, but then would have to have the same name inside the closure. Instead of using function(){} you could use a callback which is how filter was designed.

The reference is done implicitly by the definition of .filter, you can read more here: http://msdn.microsoft.com/en-us/library/ff679973(v=vs.94).aspx

like image 30
Travis J Avatar answered Sep 25 '22 23:09

Travis J