How ES6 Arrow Function Can Help You in JavaScript

An Arrow function is a compact alternative to a traditional function expression, but is limited and can’t be used in all situations.

Syntax:

//One param. With simple expression return is not needed:
param => expression

//Multiple params require parentheses. With simple expression return is not needed:
(param1, paramN) => expression

//Multiline statements require body brackets and return:
param => {
  let a = 1;
  return a + param;
}

//Multiple params require parentheses. Multiline statements require body brackets and return:
(param1, paramN) => {
   let a = 1;
   return a + param1 + paramN;
}


Advanced syntax

//To return an object literal expression requires parentheses around expression:
params => ({foo: "a"}) // returning the object {foo: "a"}

//Rest parameters are supported:
(a, b, ...r) => expression

//Default parameters are supported:
(a=400, b=20, c) => expression

//Destructuring within params supported:
([a, b] = [10, 20]) => a + b;  // result is 30
({ a, b } = { a: 10, b: 20 }) => a + b; // result is 30

 

One Comment

  1. 20bet September 7, 2023 at 12:18 pm - Reply

    Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.

Leave A Comment