ES6 – Arrow Functions

This is one more new addition to Javascript in ES6. Let’s assume we have an array have birthYear and a function to calculate age(our previous example).

*in map method we have access to the current element, the current index and also the entire years array.

Let’s now see how we would write the same code in ES6

If we have more than one parameter, we would be writing the code in the below format.

In case we are having few code of lines before the return statement, we would handle the code in the below manner.

Apart from the arrow function helping us to write code in a more simpler way. The major use of arrow function is that it share the surrounding this keyword. This means that unlike normal functions, arrow functions do not get their this keyword.

They use the this keyword of the function they are written in. That is why we call that they are having a LEXICAL THIS variable.

Let’s write some code in ES5 using this keyword

Let us now see the output of this on a browser after clicking the color green.

Instead of getting the position and color values we have received a undefined about which we have seen in previous blogs. This is because, only in a method call the this keyword point to that object. But in a regular function call the this keyword will always point to the global object, which is the window object in this case. Also, the callback function we have in the above code is not a method call, it is a regular function call.

So as to handle this situation in ES5, it is advised to create a new variable and assign this keyword to it.

Let’s see how it workd in case of ES6, it share the surrounding this keyword. Writing the same code in ES6 using arrow functions.

*Arrow functions uses it surrounding this keyword.

Let’s now change function at line 163 to arrow function and see what happens.

We get a undefined. This is because the function we just changed also share the Lexical This keyword from its surroundings, and surrounding of this is the global context, which in this case is the window object.

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts