What is Javascript Arrow Function?
Javascript Arrow functions are the shorter version of a javascript function. With the help of arrow functions, we can write any function in javascript in a concise way.
For Example: Consider a function that returns greater value among 2 numbers as shown below:
Function returning greater value among 2 numbers |
This function can be written as shown in the below image as an arrow function:
Arrow function returning greater number among 2 numbers |
Syntax of Arrow function
The arrow function is written as shown in the below image
Syntax of Arrow Function |
For 1 parameter, the syntax would be:
Parenthesis is not needed for one parameter |
If there is no parameter, the function can be written as follows:
Arrow function with no parameter |
Arrow functions vs Normal functions
The main advantage of using the arrow function is that the object accessed by this keyword inside the function depends on the enclosing content unlike normal functions in javascript.
Example showing how "this" is bound in normal function vs that in arrow function
Consider the below example:
Example of how "this" keyword behaves in a normal function |
Here, when you click the anchor tag, it should display the text "Click" in the alert box, but all we get is as shown in the below image:
Alert box on clicking the anchor tag |
This happens because this inside setTimeout function binds to the setTimeout() function. Check this example on jsfiddle.
Let's change the setTimeout callback function into the arrow function as shown below:
setTimeout with arrow function as a callback |
This will show the anchor text on click because "this" inside the arrow function will be inherited from the parent i.e the anchor click event. Thus, "this" inside the arrow functions are inherited from the enclosing content.
The output would be as shown below:
Output with the arrow function |
You can check this example on jsFiddle. I Hope, you got the basic idea of what arrow functions are. For any queries or feedback, you can write to me at [email protected]. To get notified for the releases, subscribe through email.