How ES6 Arrow Function Can Help You in JavaScript
Javascript

JavaScript: How ES6 Arrow Function Can Help You

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

 

Leave a Reply

Your email address will not be published. Required fields are marked *