Select Page
JavaScript ES6+ : Arrow Functions
Jayman Pandya
Apr 14, 2020

Arrow functions are new in ES6. They are concise, have implicit returns and does not rebound the value of “this” when arrow function is used inside another function.

const moduleNames = ["One", "Club", "Finance"];

// Map names without Arrow functions
const moduleFullNames = moduleNames.map(function(moduleNames) {
  return `Zip ${moduleNames}`;
});
console.log(moduleFullNames); // The console will print ["Zip One", "Zip Club", "Zip Finance"]


// Map names with Arrow functions
const moduleFullNamesWithArrowFunction = moduleNames.map((moduleNames) => {
  return `Zip ${moduleNames}`;
});
console.log(moduleFullNamesWithArrowFunction); // The console will print ["Zip One", "Zip Club", "Zip Finance"]

You can skip wrapping the variable in parenthesis when only one parameter is passed

// Map names with Arrow functions without parenthesis
const moduleFullNamesWithArrowFunctionNoBrackets = moduleNames.map(moduleNames => {
  return `Zip ${moduleNames}`;
});
console.log(moduleFullNamesWithArrowFunctionNoBrackets); // The console will print ["Zip One", "Zip Club", "Zip Finance"]

Implicit returns

// Map names with Arrow functions without parenthesis
const moduleFullNamesWithArrowFunctionImplicitReturns = moduleNames.map(moduleNames => `Zip ${moduleNames}`);
console.log(moduleFullNamesWithArrowFunctionImplicitReturns); // The console will print ["Zip One", "Zip Club", "Zip Finance"]

Arrow functions are always anonymous. If you want to add an identifier to the Arrow function, you can assign it to a variable

// Assign Arrow function to a variable and map the module names in shorthand
const namedArrowFunction = (moduleNames) => { alert(`Zip ${moduleNames}`)};
namedArrowFunction('One'); // The alert box will show "Zip One"

Implicit returns with an Object Literal using Arrow functions

const visitors = ['Rashmi', 'Jayman'];

//Return the object using the Map function
const name = visitors.map((visitor, i) => ({name: visitor, id: i+1}));

Will output Rashmi | 1 & Jayman | 2

One more example. Try to find # of children in the club using Implicit returns using arrow functions

const agesOfPeopleInTheClub = [4, 32, 6, 9, 15, 17, 12, 24, 60];
const filterChildren = agesOfPeopleInTheClub.filter(child => child <= 18); // Will return an array [4,6,9,15,17,12]

Assign default parameter value when declaring a parameter that will be passed in a function

//Define tax & interest parameters with pre-defined values of 18% & 20% respectively
function calculateMonthlyMaintenanceBill(total, tax = 0.18, clubFees, prevOutstandings, interest = 0.20) {
  return(total + (total * tax) + clubFees + prevOutstandings + (prevOutstandings * interest));
}

//Passing the parameter as undefined as the value is already setup. This can be overridden with any other value also.
const MonthlyMaintenanceBill = calculateMonthlyMaintenanceBill(10, undefined, 5, 10, undefined);

console.log(MonthlyMaintenanceBill);

While Arrow function is very useful and effective shorthand way of writing functions, it cannot be used in every scenario. Here are 4 scenarios in which you cannot use Arrow functions

#1 : When you need access to “this“, as “this” keyword does not get rebound when you use Arrow Function

// "this" won't work here
const button = document.querySelector('.button');

button.addEventListener('click', => {
  console.log(this) //Output of 'this' will be Window instead of button.
});

// "this" will work here
const newButton = document.querySelector('.button');

newButton.addEventListener('click', function() {
  console.log(this) //Output of 'this' will be Button as intended
});

#2 : When you want a method to bind to an object

// "this" won't work here
const member = {
  memberSince :76,
  update: () => {
    this.memberSince++;
  }
}

// "this" will work here
const member = {
  memberSince : 76,
  update: function() {
    this.memberSince++;
  }
}

#3 : When you need to add the prototype

// "this" won't work here
class MemberCars {
  constructor(nameOfMember, make, model, color) {
    this.nameOfMember = nameOfMember;
    this.make = make;
    this.model = model;
    this.color = color;
  }
}

const a401 = new MemberCars('Jayman', 'Volkswagen', 'Vento', 'White');
const d1306 = new MemberCars('Rashmi', 'Hyundai', 'Grand i10', 'Grey');
const b704 = new MemberCars('Hazel', 'Toyota', 'Corolla Altis', 'Blue');

MemberCars.prototype.summarize = () => {
  return`${this.nameOfMember} owns ${this.color} ${this.make} ${this.model}.`
}

// "this" will work here
class MemberCars {
  constructor(nameOfMember, make, model, color) {
    this.nameOfMember = nameOfMember;
    this.make = make;
    this.model = model;
    this.color = color;
  }
}

const a401 = new MemberCars('Jayman', 'Volkswagen', 'Vento', 'White');
const d1306 = new MemberCars('Rashmi', 'Hyundai', 'Grand i10', 'Grey');
const b704 = new MemberCars('Hazel', 'Toyota', 'Corolla Altis', 'Blue');

MemberCars.prototype.summarize = function() {
  return`${this.nameOfMember} owns ${this.color} ${this.make} ${this.model}.`
}

#4 : When you need to access arguments object

// "this" won't work here
const itemsOrdered = () => {
  const items = Array.from(arguments);
  return items.map((item, i) => {
    return `${i + 1} | ${item}`;
  })
  console.log(arguments);
}

// "this" will work here
const itemsOrdered = function() {
  const items = Array.from(arguments);
  return items.map((item, i) => {
    return `${i + 1} | ${item}`;
  })
  console.log(arguments);
}

Arrow functions are very good at some places and can cause undefined errors, so have to be used carefully.

As Uncle Ben has said “With great power comes great responsibility”.

Peace ✌️

Let's Talk

If you liked what you have seen, then let’s connect and make something amazing together.

Email me at converse@jaymanpandya.com or send a DM on my twitter @jaymanpandya