Skip to content

Instantly share code, notes, and snippets.

@anthonyalvarez
Created November 15, 2018 17:49
Show Gist options
  • Select an option

  • Save anthonyalvarez/14c2f8cca09629dd26ebb2bb0836aa04 to your computer and use it in GitHub Desktop.

Select an option

Save anthonyalvarez/14c2f8cca09629dd26ebb2bb0836aa04 to your computer and use it in GitHub Desktop.
Arrow Functions

Arrow Functions

Functions are one of the primary data structures in JavaScript; they've been around forever. ES6 introduces a new kind of function called the arrow function. Arrow functions are very similar to regular functions in behavior, but are quite different syntactically. The following code takes a list of names and converts each one to uppercase using a regular function:

const upperizedNames = ['Farrin', 'Kagure', 'Asser'].map(function(name) { 
  return name.toUpperCase();
});

The code below does the same thing except instead of passing a regular function to the map() method, it passes an arrow function. Notice the arrow in the arrow function ( => ) in the code below:

const upperizedNames = ['Farrin', 'Kagure', 'Asser'].map(
  name => name.toUpperCase()
);

The only change to the code above is the code inside the map() method. It takes a regular function and changes it to use an arrow function.

Convert an ES5 function to an ES6 arrow function

const upperizedNames = ['Farrin', 'Kagure', 'Asser'].map(function(name) { 
  return name.toUpperCase();
});

With the function above, there are only a few steps for converting the existing "normal" function into an arrow function.

• remove the function keyword
• remove the parentheses
• remove the opening and closing curly braces
• remove the return keyword
• remove the semicolon
• add an arrow ( => ) between the parameter list and the function body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment