Arrow Functions in ES6

Easiest way to think of Arrow Functions is to think of them as anonymous functions.
Please note that you might find them acting differently when working with ‘this’ though!
Example, lets see if we can gather all ford cars total km:

const cars = [
 {brand: 'Volvo', km: 20000},
 {brand: 'Ford', km: 60000},
 {brand: 'Toyota', km: 50000},
 {brand: 'Ford', km: 50000},
 {brand: 'Ford', km: 70000},
 {brand: 'Ferrari', km: 20000}
]
const totalFordsKm = cars
  .filter(function(event){
     return event.brand === 'Ford';
  })
  .map(function(event) {
    return event.km;
  })
  .reduce(function(prev,km) {
    return (prev || 0) + km;
  });

console.log(totalFordsKm);

If we refactor this with arrow functions we get:

const totalFordsKm = cars
  .filter((event) => {
     return event.brand === 'Ford';
  })
  .map((event) => {
    return event.km;
  })
  .reduce((prev,km) => {
    return (prev || 0) + km;
  });

console.log(totalFordsKm);

We can continue to refactor this,
If the code is 1 statement we can return the statement implicit without writing return! A unique arrow function ability.

const totalFordsKm = cars;
  .filter((event) => event.brand === 'Ford')
  .map((event) => event.km)
  .reduce((prev,km) => (prev || 0) + km);

console.log(totalFordsKm);

We can continue to refactor this by removing the parenthesis that wraps just (event):

const totalFordsKm = cars
  .filter(event => event.brand === 'Ford')
  .map(event => event.km)
  .reduce((prev,km) => (prev || 0) + km);
  console.log(totalFordsKm);

If you find that this is getting to complicated for a single statement you can break some reusable functions out and instead call them:
Note that I renamed km to X as this reduce function could be used for much other things that just this use case.

  const reduceTotal = (prev, x) => (prev || 0 ) + x;
  const totalFordsKm = cars
  .filter(event => event.brand === 'Ford')
  .map(event => event.km)
  .reduce(reduceTotal);

  console.log(totalFordsKm);

Add your comment