Everything you need to know about ES6 Arrow Functions and lexical ‘this’

I have got you covered!!

Before diving into any new topic it’s always important to understand WHY we should use it. So lets first understand that.

Benefits of ES6

  1. They help in writing concise JavaScript functions.
  2. They have implicit returns, which allows us to write one-liner functions.
  3. They do not rebind this, which is very useful for click handlers.

Its OK if you don’t understand the complete meaning of all of them now because by the end of this tutorial you will.

[Did You Know: Arrow Function is the most popular ES6 feature]

Let’s get you started with the basic syntax of Arrow functions and then we will explore the examples.

Arrow Function Syntax

// No parameters
() => { statements }
// single parameter
(param) => { statements }
param => { statements }
// multiple parameters
(param1,param2,....paramN) => { statements }
// Returning objects
// enclose objects by parenthesis so they can be treated as objects
(param1,param2) => ( { id: 1 , key: value });

That's it!! Easy right!!You now know the syntax for Arrow functions.So let’s get your hands dirty. Throughout all examples, I am going to provide a comparison between ES6 and ES5 to help you wrap your mind around new arrow functions.

Example 1:

var imgUrlArray = [
imgUrl1,
imgUrl2
];
//ES5
imgUrlArray.map(function (img){
return img;
});
//ES6
imgUrlArray.map(img => img);

With ES6 you get to skip function keyword and return keyword as well some parenthesis, braces and semicolons.

Example 2:

// Expressions// ES5
var plusOne = [1,2,3,4,5].map(function(num){ return num + 1 });
// ES6
var plusOne = [1,2,3,4,5].map(num => num + 1); // implicit return

Example 3:

Promise chains can be prettified by using arrow functions.Since the return is implicit, there is no need to write it.This makes promises less error prone and easy to understand and work with.

// ES5
someFunctionReturningPromise
.then(function(data1){
console.log(data1);
}).then(function(data2){
console.log(data2);
}).catch(function(err){
console.log(err);
});
// ES6
someFunctionReturningPromise
.then((data1) => console.log(data1) )
.then((data2) => console.log(data2) )
.catch((err) => console.log(err) );

Lexical ‘ this’

So in the past you would have used statements like —

.bind(this)
var abc = this;

This is known as Lexical Scoping.Earlier, every new function defined its own this value. This proved to be less than ideal for an object-oriented style of programming. An arrow function does not newly define its own this when it's being executed.The value of this is always inherited from the enclosing scope.

// ES5
function Counter(){
this.seconds = 0;
window.setInterval(function() {
this.seconds++;
}.bind(this), 1000);
}
//ES6
function Counter(){
this.seconds =0;
window.setInterval( () => this.seconds++,1000 );
}

Most people are aware of this feature of ES6 but very few people are aware of the fact that ES6 arrow functions don’t bind their own arguments either.

const funct = () => {
console.log(arguments); // This will throw reference error
}
// undefined

Now with ES6, it is not possible to get an indefinite amount of arguments inside an array

When to Avoid them??( You have been warned! )

After learning about Arrow Functions you might be tempted to replace all your ES5 functions, but before you do that, it’s important to understand Arrow functions cannot be used as

  • Constructors
var Person= (param) => {
this.name = param;
}
var Boy = new Person('Ram');
// Throws error that Person is not a constructor
  • Callback functions with Dynamic Context

It is very common to attach event Listeners to DOM elements like button clicks. An event triggers the handler function with this as the target element.

var button = document.getElementById('myButton');  
button.addEventListener('click', () => {
console.log(this === window); // true and this != button
this.innerHTML = 'Clicked button';
});
  • With new Keyword
var func = () => { console.log("Hello"); };
var func1 = new func();
// Uncaught TypeError: func is not a constructor

Arrow functions don’t work as constructors and don’t have [[Construct]] internal method.

So in such cases, you should use function().

Want to know more?? Need more examples?? Here’s an article I found really useful

If you were able to learn something from this tutorial please don’t forget to give it claps 👏

Find more such posts on my new personal blog https://twishasaraiya.github.io/

--

--

Twisha Saraiya
Beginner's Guide to Mobile Web Development

Tech-enthusiast, Open Source Lover, Student, Optimist, Loves to read novels