Arrow Functions

ES6 introduced arrow function syntax. Arrow functions remove the need to type out the keyword function every time you need to create a function.

I. How to declare an arrow function

To make an arrow function, we name it a variable. After the parameters, we add the arrow sign.

const add = (num1, num2) => {
  return num1 + num2;
}

console.log(add(3,4)); // 7

is similar to:

function add(num1, num2) {
  return num1 + num2;
}

console.log(add(3,4)); // 7

II. Shorten the arrow function

We can shorten the arrow function above as well.

const add = (num1, num2) =>  num1 + num2;

console.log(add(3,4)); // 7

Rules

  1. Functions that take only a single parameter do not need that parameter to be enclosed in parentheses. However, parentheses are required if a function takes zero or multiple parameters.
// Zero parameters
const functionName = () => {};

// 1 parameter
const functionName = (para1) => {};

// 2 parameters
const functionName = (para1, para2) => {};
  1. A function body with a single-line block does not need curly braces.
// Single-line block
const multiNumbers = (number) => number * number;

// Multi-line block
const multiNumbers = (number) => {
  const multi = number * number;
  return multi;
};