Sitemap
Steven Zhu

Steven Zhu

The Javascript Arrow Function

2 min readMar 26, 2020
Press enter or click to view image in full size

The arrow function or “fat arrow” function was introduced to Javascript in ES6 with the intent to provide a shorter syntax for writing functions. Since their introduction, the usage of arrow functions has become widespread throughout the Javascript community. So what are the major benefits of adopting this notation?

  1. Syntax

One of the biggest advantages is that is allows developers to accomplish the same tasks in fewer lines of code. Say for example you had a function that added two numbers together. Using the regular function declaration, it might look something like this …

function addNumbers(a, b) {
return a + b;
}

However, the same function can expressed with less code using an arrow function.

let addNumbers = (a, b) => a + b

An arrow function does not require curly brackets if only expression is present, however they are required if there is more than one statement.

Additionally if a function only has one argument, then the parentheses are not required around the argument. For example:

let addFive = a => a + 5

2. Binding of ‘this’

Get Steven Zhu’s stories in your inbox

Join Medium for free to get updates from this writer.

With a traditional function declaration, ‘this’ refers to whatever context in which the function is called in. Take this piece of code for example:

function countUp() {
this.count = 0;
setInterval(function add() {
this.count++
console.log(this.count);
}, 1000);
}
let number = new countUp()

If this section of code were to be run in the browser console, the result would be this:

let number = new countUp()//NaN
//NaN
//NaN
//...

Why is this happening? When the function setInterval is being called, it is actually being bound to the global object. There is no declared object for the function setInterval . This issue can be solved by binding ‘this’ to the scope of the function.

function countUp() {
this.count = 0;
setInterval(function add() {
this.count++
console.log(this.count);
}.bind(this), 1000);
}
let number = new countUp()//1
//2
//3
//...

Guess what? Arrow functions automatically bind ‘this’ to the caller of the function.

function countUp() {
this.count = 0;
setInterval(() => {
this.count++;
console.log(this.count);
}, 1000)
}
let number = new countUp()//1
//2
//3
//...

The use of methods like a call() , apply() , and bind() cannot be used to change the value of ‘this’ for arrow functions.

Cases To Think About

Arrow functions cannot be used to create constructors. Using a new with arrow functions will throw an error. This is because arrow functions, like built-in javascript methods, do not have their own prototypes or internal methods.

It is also worthwhile to take a look at your code to make sure using arrow function notation doesn’t result in less readability. Arrow functions can make code harder to read when looking at it straight on.

--

--