I'm trying to use ES6 arrow function with .filter
to return adults (Jack & Jill). It appears I cannot use an if statement.
What do I need to know in order to do this in ES6?
var family = [{"name":"Jack", "age": 26},
{"name":"Jill", "age": 22},
{"name":"James", "age": 5 },
{"name":"Jenny", "age": 2 }];
let adults = family.filter(person => if (person.age > 18) person); // throws error
(8:37) SyntaxError: unknown: Unexpected token (8:37)
|let adults = family.filter(person => if (person.age > 18) person);
My working ES5 example:
let adults2 = family.filter(function (person) {
if (person.age > 18) { return person; }
});
Arrow functions either allow to use an expression or a block as their body. Passing an expression
is equivalent to the following block
However,
is not an expression,
if
is a statement. Hence you would have to use a block, if you wanted to useif
in an arrow function:While that technically solves the problem, this a confusing use of
.filter
, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to.filter
should return a Boolean, i.e.true
orfalse
, indicating whether the element should be included in the new array or not.So all you need is
In ES5:
You can't implicitly return with an
if
, you would need the braces:It can be simplified though: