0

I have found an example of somebody using the .filter() function without passing it a function as a parameter. I am puzzled as to how this works, here is an example of the code:

var integers = [1,2,3,4,5,6,7,8,9,10];
var even = integers.filter(int => int % 2 === 0);
console.log(even);   // [2,4,6,8,10]

I am confused because I thought that filter must take a function as an argument, but instead is comparing "int" against "int % 2 === 0".

How is this happening? why does "int" not have to be declared and why can filter accept something that isn't a function?

Thanks!

Gerard Simpson
  • 2,026
  • 2
  • 30
  • 45
  • 2
    that is a function, a fat arrow function. it's new in "ES6"... it's the same as `function(int){return int % 2 === 0;}`. `int` is the formal parameter. – dandavis Mar 26 '16 at 04:08
  • 1
    It's using arrow function from ES6 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Cesar William Alvarenga Mar 26 '16 at 04:09

2 Answers2

2

The parameter of the example IS a function, arrow function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

It's basically a shorthand syntax for declaring a function which returns the first statement;

0

That's a function defined using the "fat arrow" notation (=>). It's also called a lambda and is new in ES6.

djechlin
  • 59,258
  • 35
  • 162
  • 290