0

I was looking at some frontend guidelines on GitHub and saw the following code sample:

// good
const createDivs = howMany => {
  if (!howMany) return;
  document.body.insertAdjacentHTML("beforeend", "<div></div>");
  return createDivs(howMany - 1);
};
createDivs(5);

What does the => do and what is it called? I have never seen this idiom before. I tried looking it up but do not know its name and the MDN documentation does not show it.

Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47
Robert
  • 10,126
  • 19
  • 78
  • 130
  • 4
    It's being implemented in ECMA6. `howMany => {}` is a shorhand for `function howMany () {}`. – Davion Sep 06 '15 at 17:48

2 Answers2

3

From the MDN documentation on arrow functions:

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous.

Besides the fact that they are a more concise way of writing an anonymous function, arrow functions have the benefit of binding this in the function expression. Thus, the pattern typically used with bind:

document.addEventListener('click', function myHandler (event) {
    console.log(event);
}.bind(this));

becomes

document.addEventListener('click', (event) => console.log(event));
j08691
  • 204,283
  • 31
  • 260
  • 272
Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90
1

What you're looking at is an arrow function expression. It's a shorter way of writing a function expression.

This example from Mozilla illustrates the advantage of defining a function with an arrow expression:

var a = [
  "Hydrogen",
  "Helium",
  "Lithium",
  "Beryl­lium"
];

var a2 = a.map(function(s){ return s.length });

var a3 = a.map( s => s.length );

Observe that s => s.length is shorter than the traditional equivalent function(s){ return s.length }. It will be easier to read, too, once we get used to seeing this form.

Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47