As I Understand — Arrow Functions

Vivek Molkar
Nov 3 · 2 min read

What is an arrow function?

Arrow functions are not just a “shorthand” for writing small stuff. Apart from being just a “shorthand” for writing small stuff but also have some very specific and useful features.

To begin with, let’s see how we can write our good old hello world program with the help of arrow functions.

Looks Impressive, Arrow functions allows us to have an implicit return:
we can return values without having return keyword.
When we work with expression bodies (single-line functions) this works.

Let us have a look at the syntax for arrow functions?

We can discuss 3 cases while we write an arrow function:

  1. No parameters: Empty parentheses followed by => and then expression body or statement body.
  2. Single parameter: We can omit the parentheses around the parameter.
  3. Multiple parameters: Enclose the parameters into the parentheses followed by => then expression body or statement body.

So far sounds good. Do we have any other benefit to use the arrow functions? Yes, apart from the concise syntax, another benefit is the lexical binding of this keyword. It means that it uses this from the code that contains the arrow function. Before arrow functions, every new function defined its own this.

Depending on how the function was called the value of this differed.

  1. A new object in the case of a constructor.
  2. undefined in strict mode function calls.
  3. The base object if the function was called as an “object method”.

Let's look at an example to understand.

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

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

This article discussed the two main benefits of arrow functions:

  1. Shorter Syntax
  2. No binding of this
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade