AppDividend
Latest Code Tutorials

Javascript Arrow Function Example | ES6 Arrow functions Tutorial

0 98

Get real time updates directly on you device, subscribe now.

Javascript Arrow Function Example | ES6 Arrow functions Tutorial is today’s topic. ES2015 (More commonly referred to as ES6) introduced Arrow Functions into JavaScript. Arrow functions have more concise syntax for writing function expressions. Arrow Functions are one of the most effective changes in ES6/ES2015, and they are widely used nowadays. Arrow functions were introduced in ES6 / ES2015, and since their introduction in JS, they changed how JavaScript code looks and works forever.

Javascript Arrow Function Example

Arrow Functions have two main benefits which are following.

  1. A shorter syntax then typical javascript functions.
  2. No binding of this keyword.

Let us see the traditional function syntax.

function funcName() {
   // func body
}

funcName()

Now, let us see ES6 version syntax.

const funcName = () => {
   // func body
}

funcName()

If the function body contains just the single statement, you can omit the brackets and write all on the single line like the following code.

const funcName = () => your code here like multiplication

You do not even write the return statement. It automatically returns the value. Refer to the above syntax; we can write a function like this.

// app.js

const square = (x) => x * x;
console.log(square(21));

See the output in the console. I am using Node.js to run the above file.

 

Javascript Arrow Function Example | ES6 Arrow functions Tutorial

Thanks to this short syntax, we can use the arrow function in small or no bodily functions which returns in a single line of code like the above example.

If we are using the traditional syntax, then the code looks like this.

// app.js

function square(x) {
	return x * x;
}

console.log(square(21));

Breakdown of Syntax of Arrow Function

Here’s what an arrow function looks like.

(parameters) => { statements }

Which is equal to this in traditional syntax.

function (parameters) {
 // statements
}

If there is no parameter, then the arrow function looks like this.

() => { statements  }

How this Works In Arrow Function

This keyword is the concept that can be complicated to grasp at first, and it is complicated because it changes its behavior depending on the context like the mode of JavaScript. It’s important to clarify these concepts because arrow function has very different compared to the regular functions.

Arrow function and Traditional function works differently when defined as a method of an object. In the regular function, this refers to the object so that you can do like this.

// app.js

const Laptop = {
	model: 'MacBook Air',
	manufacturer: 'Apple',
	fullProductName: function() {
		return `${this.manufacturer}'s ${this.model}`;
	}
};

console.log(Laptop.fullProductName());

The output is following.

 

How this Works In Arrow Function

Now, let us take the following scenario and use the arrow function inside the object.

// app.js

const Laptop = {
	model: 'MacBook Air',
	manufacturer: 'Apple',
	fullProductName: () => {
		return `${this.manufacturer}'s ${this.model}`;
	}
};

console.log(Laptop.fullProductName());

Run the file and see the output.

No binding of this in Arrow Function

 

That means the arrow function does not work in the Object context in ES6 because this scope is referred to the calling function and not the function itself. Arrow functions cannot be used as constructors either, when instantiating an object will raise the TypeError exception. In that scenario, the regular or traditional function is required where the dynamic context is not needed.

If you are familiar with React.js then, you have faced one issue regarding this binding scope.

Related Posts
1 of 37

When we write the form’s textbox’s onChange() event, we have faced this scope issue. At that time, we need to add the function expression inside the constructor() of React.js’s class. Otherwise, we do not get the textbox value inside the onChange() event’s function.

At that time, we can also use the arrow function to escape this binding keyword issue.

In the arrow function,  this is bound lexically. Simply put, this means that this will keep its meaning from its original context.

No binding of this

Let us see the following example.

// app.js

function Person() {
	this.age = 0;
	setInterval(function() {
		this.age++;
		console.log(this.age);
	}, 1000);
}
var user = new Person();

In the above example, we have used Function Prototype which behaves as a class in traditional Javascript. When we run the example, we could not see the age in the console. See the output.

 

ES6 Arrow functions Tutorial

That means the reference to this keyword is not lexical. To solve this problem, we can use the arrow function and now it will begin to display the numbers. See the following code.

// app.js

function Person() {
	this.age = 0;
	setInterval(() => {
		this.age++;
		console.log(this.age);
	}, 1000);
}
var user = new Person(); /* eslint-disable-line no-unused-vars */

The output is following.

 

Javascript ES6 — Arrow Functions and Lexical `this

An arrow function does not have its own this scope; it uses the this value of the enclosing lexical context is used, i.e., Arrow functions follow the standard variable lookup rules. So while searching for this which is not present in the current scope, they end up finding this from its enclosing scope. That is why we can see the output in the console.

This keyword’s behavior depends on the context; you are working on that is why sometimes, it will not give the value that you are expected.

Finally, Javascript Arrow Function Example | ES6 Arrow functions Tutorial is over.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.