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
  • 11,641
  • 2
  • 27
  • 46
Robert Rocha
  • 9,510
  • 18
  • 69
  • 121
  • 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
  • 197,815
  • 30
  • 248
  • 265
Nick Tomlin
  • 27,264
  • 11
  • 59
  • 87
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
  • 11,641
  • 2
  • 27
  • 46