Arrow functions are undoubtedly one of the more popular features of ES6. They introduced a new way of writing concise functions.

Here is a function how is written in ES5 syntax:

function calculateAge(birthYear) { return 2020- birthYear } calculateAge(1984); // 36

Now, here is the same function expressed as an arrow function:

const calculateAge = birthYear => 2020 - birthYear calculateAge(1984); // 36

It’s much shorter! We are able to omit the curly braces and the return statement due to implicit returns (but only if there is no block — more on this below).

It is important to understand how the arrow function behaves differently compared to the regular ES5 functions.

Variations

One thing you will quickly notice is the variety of syntaxes available in arrow functions. Let’s run through some of the common ones:

1. No parameters

If there are no parameters, you can place empty parentheses before = .

() => 36

In fact, you don’t even need the parentheses!

_ => 36

2. Single parameter

With these functions, parentheses are optional:

x => 36 || (x) => 36

3. Multiple parameters

Parentheses are required for these functions:

(x, y) => 36

4. Statements (as opposed to expressions)

In its most basic form, a function expression produces a value, while a function statement performs an action.

With the arrow function, it is important to remember that statements need to have curly braces. Once the curly braces are present, you always need to write return as well.

Here is an example of the arrow function used with an if statement:

let is_friend = (param) => { if (param === true) { return 'Can Join chat'; } else { return 'No access on chat channel'; } }

5. “Block body”

If your function is in a block, you must also use the explicit return statement:



let addValues = (x, y) => { return x + y }

6. Object literals

If you are returning an object literal, it needs to be wrapped in parentheses. This forces the interpreter to evaluate what is inside the parentheses, and the object literal is returned.

x =>({ y: x })

7. Syntactically anonymous

It is important to note that arrow functions are anonymous, which means that they are not named.

This anonymity creates some issues:

Harder to debug

When you get an error, you will not be able to trace the name of the function or the exact line number where it occurred.

2. No self-referencing

If your function needs to have a self-reference at any point (e.g. recursion, an event handler that needs to unbind), it will not work.

Main benefit: No binding of ‘this’

In classic function expressions, the this keyword is bound to different values based on the context in which it is called. With arrow functions, however, this are lexically bound. It means that it uses this from the code that contains the arrow function.

For example, look at the setTimeout function below:

// ES5 var obj = { id: 65, counter: function counter() { setTimeout(function() { console.log(this.id); }.bind(this), 850); } };

In the ES5 example, .bind(this) is required to help pass the this context into the function. Otherwise, by default this would be undefined.

// ES6 let obj = { id: 65, counter: function counter() { setTimeout(() => { console.log(this.id); }, 850); } };

ES6 arrow functions can’t be bound to a this keyword, so it will lexically go up a scope, and use the value of this in the scope in which it was defined.

When you should not use Arrow Functions

After learning a little more about arrow functions, I hope you understand that they do not replace regular functions.

Here are some instances where you probably wouldn’t want to use them:

Object methods

When you call cat.jumps , the number of lives does not decrease. It is because this is not bound to anything, and will inherit the value of this from its parent scope.

let player = { lives: 3, jumps: () => { this.lives--; } }

2. Callback functions with dynamic context

If you need your context to be dynamic, arrow functions are not the right choice. Take a look at this event handler below:

let button = document.getElementById('press'); button.addEventListener('click', () => { this.classList.toggle('on'); });

If we click the button, we would get a TypeError. It is because this is not bound to the button, but instead bound to its parent scope.

3. When it makes your code less readable

It is worth taking into consideration the variety of syntax we covered earlier. With regular functions, people know what to expect. With arrow functions, it may be hard to decipher what you are looking at straightaway.

When you should use them

Arrow functions shine best with anything that requires this to be bound to the context, and not the function itself.