ES6 Arrow Functions

ES6 Arrow Functions

In 2015, the new ECMAScript edition ES6 brought Arrow functions to the JavaScript language. At a first glance they can be seen as a fancier way of writing functions and overwhelming to deal with as a new developer. So, in this article let us learn how to use arrow functions and some key differences from the traditional functions.

Syntax

Let us write a function which takes a name and greets the user. We would then slowly convert it into an arrow function step by step. The traditional way of writing a function would be -

function greetUser(name) {
  return `Greetings ${name}`
}

Now let us try to convert this into an arrow function.

  • Step 1 : Remove the function keyword in the declaration and create a new variable with the function name.
    const greetUser =
    
  • Step 2 : Add the parameters inside a parenthesis i.e. () and put them after the equals sign
    const greetUser = (name)
    
  • Step 3 : All that is left now is to add the => sign formed using = and > after the parameters and move the remaining function body after it.
    const greetUser = (name) => {
      return `Greetings ${name}`
    }
    
    Now, that's how you write an arrow function. But WAIT!! You would say what's the big deal about using arrow functions if all they do is eliminate the function keyword. Just wait for the fun part, let us cut down some more stuff from the above declaration.

Implicit Return

While using the traditional functions, we need to use the return keyword every time we want to return some data from that function. Arrow functions provide this new feature where, if you have just one line your function the return statement can be eliminated. Making them my go-to choice for one liners and anonymous/lambda functions.

const greetUser = (name) => `Greetings ${name}`

And if your function does no return any thing then you can just put curly braces around the function body

const nameLogger = (name) => { console.log(name) }

Note : If you want to return an object literal from a one liner arrow function, put your function body inside parenthesis.

const getUserDetails = (id) => ({firstName: 'John', lastName: 'Doe'})

Arrow Functions with Single Parameter

If the arrow function has only a single parameter, you can eliminate the parenthesis as well.

const greetUser = name => `Greetings ${name}`

Note : Incase of no parameters, the parenthesis are required

const greet = () => `Greetings`

Anonymous Functions

As previously said, arrow functions are a prefect candidate for anonymous / lambda functions.

document.addEventListener('click', function () {
  console.log('Clicked')
}
document.addEventListener('click', () => {
  console.log('Clicked')
}

Async Functions

We can also write async functions using an arrow expression. Just perform the above 3 steps and add the async keyword just before the paramerters.

async function getDataFromDB(url) {
  try {
    const res = await fetch(url);
    const data = await res.json();
    await console.log(data);
  } 
  catch(err) {
    console.error(err)
  }
}
const getDataFromDB = async url =>  {
  try {
    const res = await fetch(url);
    const data = await res.json();
    await console.log(data);
  } 
  catch(err) {
    console.error(err)
  }
}

Arguments array

The traditional functions have access to an arguments array which is a special array containing all parameters of the function. Arrow functions do nothave an arguments array.

function greetUser (name) {
  console.log(`Greetings ${arguments[0]}`)
}
greetUser('John')
// Greetings John
const greetUser = name =>  {
  console.log(`Greetings ${arguments[0]}`)
}
greetUser('John')
// ReferenceError: arguments is not defined

Arrow Functions as Methods

It is common for object methods to access information stored inside the object. This is done using the 'this' keyword followed by the name of the required property. In traditional functions, 'this' gets bound to the parent scope (user Object in our case).

const user = {
  username: 'john_2',
  getUsername: function() { return this.username},
}
user.getUsername()
// john_2

Arrow Functions do not have their own 'this' and would refer its value from their lexical scope. In the current scenario, this is referring to the global object in non-strict mode and undefined in strict mode.

const user = {
  username: 'john_2',
  getUsername: () =>  this.username,
}
user.getUsername()
// undefined

Summary

  • The syntax of an arrow function is as follows :
    const functionName = (param1, param2) => statement
    
  • Parenthesis around parameters can be omitted incase of single parameter.
  • Return statement can be omitted incase of a one liner function.
  • Arrow functions are most suitable for anonymous functions (e.g. inside map, filter, reduce).
  • The async keyword can be used with arrow functions just before the parameters.
  • Arrow functions do not have access to arguments array.
  • Arrow functions refer the this value from their lexical scope.