If you want to write a short function syntax there's no better way than the arrow function. In this article, we will go through one of the most popular ES6 features => Arrow Function. Let's start!
Let's explore the syntax and how it differs from the normal function syntax:
function helloWorld(){
console.log("Hello World"); // Hello World
}
As shown in the above example, this is the syntax for regular function we used to see, but the arrow functions came with a different syntax:
()=> console.log("Hello World"); //Hello World
Arrow functions came with the shortest and easiest way to write a function as shown , it's an anonymous function which means it can be unnamed function , it has a brackets to pass parameters directly and then what this function is going to return after arrow . It has an implicit return so no need to write a return keyword .
var incrementOne = [1,2,3,4,5].map(num => num +1) ;
console.log(incrementOne); // [2,3,4,5,6]
Here's a one line arrow function that is used to map over array and increment its element by one , as simple as that !
An arrow function could be a one line function with its parameters and return statement, it's short and easy!
One more benefit of Arrow function is the scope of “this” within an arrow function:
“this” could refers sometimes to the parent of the function which is “window” , so you need to bind this to this function's scope , but every “this” used within an arrow function will refer to this function's scope, not to the parent .
In ES5
var obj = {
id : 42 ,
timer: function timer() {
setTimeOut( function () {
console.log(this);
console.log(this.id);
},1000);
};
obj.timer() ; // this will return window object
As shown when used a regular function , “this” within this function returns the parent of the function scope which is the window object, so you need to bind “this”.
In ES6
var obj = {
id : 42 ,
timer: function timer() {
setTimeOut(() => {
console.log(this);
console.log(this.id);
},1000);
};
obj.timer() ; // this will return obj object where this scope and id defined within this scope.
Summary
-
They have shorter syntax than regular functions and could be one line function.
-
They could be anonymous and have implicit return statements.
-
"this" scope remains within the method declared in when arrow functions used as inner functions.
This is all you need to know about arrow functions, I hope you enjoyed reading this and learned something.
Don't just read about it, try it!
Happy learning!