3 ms·
Sorry, you’re right, that wasn’t a very good example. The use with `map` really is different: with a fat arrow, you can easily pick out a single property from
by Chris_Newton 12y ago
Sorry, you’re right, that wasn’t a very good example.
The use with `map` really is different: with a fat arrow, you can easily pick out a single property from each object in your container (not just whether it exists, which seems to be what you were getting at in your alternative).
But yes, the fat arrow is unnecessary in the trivial filter and reduce examples I gave. I should have provided a slightly more involved example, such as this:
items.map(item => item.interesting_property)
.filter(item => is_wanted(item, some_criteria))
.reduce((item1, item2) => combine_usefully(some_context, item1, item2), initial_value)
Now you’ve got some extra arguments to supply, so you can’t just pass the functions in directly when calling `filter` and `reduce`.
In today’s JS (meaning ES5) you would generally need the older anonymous function notation. You might still have some shortcuts available, such as `Function.bind` if the order of parameters lend themselves to convenient partial application as in the `reduce` case here:
items.map(function(item) { return item.interesting_property })
.filter(function(item) { return is_wanted(item, some_criteria) })
.reduce(combine_usefully.bind(this, some_context), initial_value)
Of course in ES6 you can just choose whichever representation you prefer:
items.map(item => item.interesting_property)
.filter(item => is_wanted(item, some_criteria))
.reduce(combine_usefully.bind(this, some_context), initial_value)
The other thing to watch out for when jumping between how today’s mainstream JS handles these kinds of manipulations and the new ES6 tools is what happens with `this`. It’s one area where current anonymous functions and the new fat arrow notation do behave differently, and unlike the `bind` example above, it’s not necessarily explicit what `this` will be when you start passing functions into other functions.