Arrow Functions

Vignesh S
4 min readApr 29, 2021

--

Table of Contents

Arrow functions are one of the most popular features of ES6. They introduced new features such as making it easier to write concise functions and handle the “this keyword.

Normal Fn vs Arrow Fn. Code Pen

When using the arrow function, the keyword function and the method name are not required by default, so we can call it an anonymous function. If it is necessary to call or reuse it, assign it to a variable and use it.

In some cases, the curly braces, parentheses, and return keyword become optional.

ES5 vs ES6

In this example above, we can see how a simple ES5 becomes an arrow function. As I mentioned in the main point, arrow functions don’t even need curly braces and return statements due to Implicit return.

What is Implicit Return?

Implicit return is, If a function body has only one line of code then no return statement is required to return a value, and no curly braces are required to cover the function body.

Implicit Return

What is Explicit Return?

Explicit return is, If a function body has more than one line of code then the return statement is must require to return a value, and curly braces are must be required to cover the function body.

Explicit Return

How Arrow Function handles argument?

An arrow function has only one argument in such a case, no parentheses are required. Which is required if there are no arguments or more than one argument is available.

Arrow Function with Single, Multiple & No params

Implicit Return value as object Literal

An object literal is a comma-separated list of name-value pairs inside of curly braces eg) {name: “Tesla”, age: 30}

In the example below, there is a small difference in both the syntax. If you closely look at the Right Syntax, the object literal is covered with parentheses.

Why only the Implicit return of Object literals have the parentheses?
As we already know, if the function body is more than one line, then it covers with curly braces. In this case, the script considered the object literal bracket as a starting block{ of the function body.

This kind of issues is not happening with external objects, array literals

Arrow Function will never be a Constructor

When trying to create an instance of ES5 function vs ES6 Function.

In the example below, the ES5 function act as a Constructor. Creating the user instance using the new keyword.

ES5 function act as a constructor

Let’s try the same in the ES6 function, what will be the result?

ES6 function trying to act as a constructor

Ans: The above result concludes the Arrow functions never be a constructor because they cannot be called with the new keyword.

Summarize the major difference related to ES5 vs ES6

Hope it will give a clear view of Arrow Functions, Please write your questions for any doubts or corrections.

Let’s discuss the next feature of ES6 in the next story.
Next topic: Spread and Rest Operators

--

--

Vignesh S
Vignesh S

No responses yet