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 as 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. Shortern the arrow function

We can shortern 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, if a function takes zero or multiple parameters, parentheses are required.
// 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;
};