Arrow Functions in JavaScript

New with ES6, arrow functions, also known as fat arrow functions, are a concise way to write function expressions:

// No parameters
var myFunc = () => {
  // Do stuff
};

// With parameters
var myFunc = (a, b) => {
  return a * b;
};

// Only 1 param, no need for parens
var myFunc = a => {
  return a * a;
};

// No brackets and implicit return
// with single-line arrow function
var myFunc = a => a * a;

// Wrap body in parens to return
// object literal
var myFunc = (first, last) =>
({ firstName: first, lastName: last });

A few key facts about arrow functions

  • You don’t need to use curly brackets if there’s only one statement in the function. In the cases where you omit the curly brackets, you can also omit the return keyword, as the return is implicit.
  • this is bound lexically, meaning that fat arrow functions don’t have their own this and that this refers to the parent scope.
  • They can’t be used as constructors or generators.
  • There’s no arguments variable available with arrow functions.
  • You’ll probably want to use a transpiler like Babel to use arrow functions today, for browsers that don’t support them yet.

Browser Support

Can I Use arrow-functions? Data on support for the arrow-functions feature across the major browsers from caniuse.com.

Search

🔎 Searching...