02 Arrow Functions - Gilian/001-ES6-By-Wes GitHub Wiki

02 - Arrow Functions

Benefits

  1. Much shorter but still readable
  2. Implicit returns (returns without the keyword)
  3. No rebinding of this when used in another function

When not to use them

  1. You need to target this and not the parent
  2. When you need the arguments object (rare)

Important

  • Always anonymous
  • no stack trace
  • you can assign a anonymous function to a variable to call it. it will not be named though
  • if you use this you will get the parent element of the function you called it on. So if you use this on the top level you will select the window

Look

// Variable
const names = ['wes', 'kait', 'lux'];

// Normal function
const fullNames = names.map(function(name) {
    return `${name} bos`;
});

// Arrow function
const fullNames2 = names.map((name) => {
    return `${name} bos`;
});

// Option with one parameter
const fullNames3 = names.map(name => {
    return `${name} bos`;
});

// With implicit return
const fullNames4 = names.map(name => `${name} bos` );

// Without parameters
const fullNames5 = names.map(() => `cool bos`);

Usefull Examples

// Variables
const race = '100m Dash';
const winners = ['Hunter Gath', 'Singa Song', 'Imda Bos'];
const ages = [23,62,45,234,2,62,234,62,34];

// Return of an object
// race: race is redundant in ES6, just go for race
// You need additional brackets around the object to embed the object
const win = winners.map((winner, i) => ({name: winner, race, place: i + 1}));

// Filter for an age
const old = ages.filter(age => age >= 60);

// Use a default for your parameters, call undefined if you want to skip a parameter
function calculateBill(total, tax = 0.13, tip = 0.15) {
    return total + (total * tax) + (total * tip);
}
const totalBill = calculateBill(100, undefined, 0.25);