Sunday, 9 September 2018

JavaScript Arrow Functions - Concise Syntax

The arrow functions in JavaScript is one of the most discussed topic of JavaScript since the release of ES6. Arrow functions are very short and concise to use. Therefore, usage of these function is quite popular among the JavaScript developers..

Syntax:

(parameters) => { statements }
 

Basically there are two benefits of the arrow functions in JavaScript..
1. Shorter Syntax: Hence reduces the syntax overhead and involves less typing.
2. No Binding of this operator: To understand this, you must have good understanding of this keyword in JavaScript. Well we will discuss this benefit of arrow functions in separate post..


In this post we will discuss about the first benefit of the arrow functions.


1. Shorter Syntax:
First take an example of the regular function.



Now you can see that above example is one of the reason for creating the arrow functions. With the help of an arrow function we can generate the same function in one line of code.



The above is example is very simple but hope you got the point..Let' take a look at few more syntaxes such as arrow function with only one statement, only with one parameter or the case of returning an expression..



You can see that in the first we removed the bracket from parameters because we just had one parameter. And In the second example we had to return an expression instead of result..Therefore we omitted the curly braces to return the expression x*y.

Let's take one more example. In this example we will use the findIndex() method of JavaScript and return the index of the first Odd number present in the array. We will implement this example in both ES5 and ES6 i.e with regular function and arrow function of JavaScript and then decide ourselves which is syntactically more concise..


 Now, I am pretty sure this example has cleared the picture of the shorter and concise syntax of the arrow funtions in javasScript..


EmoticonEmoticon