Hey everyone 👋🏻, in this blog we are going to discuss about :
- Arrow Functions V/S Regular Functions
- Advantages and Disadvantages of using Arrow Functions
Like I said in my previous blog, the arrow function is not a new concept, it is just a syntax revamp of the regular function in JS. The new syntax is very very easy, it is just a sugar coating around the old function syntax so without wasting anymore time let's start learning about arrow functions!
We are going to discuss 4 different types of functions and we'll transform them from the old rusty ES5 syntax to ES6 syntax.
4 different types are going to be:
1. A named function with no parameters.
2. A named function with one parameter.
3. A named function with two parameters.
4. An unnamed function.
As you can see in the above photo, we have to give the name of the function as a variable name and after an equal symbol
= an opening and closing parenthesis
( ) which will denote the function, leading with an arrow
=> which is nothing but an equal sign and angular bracket.
There is another way of making an one liner arrow function, you just have to give the function name as a variable name and
= sign leading with
=> arrow and the statement you want to return.
There is no change except in the parenthesis
( ) in which we will pass our parameters.
Isn't this cool??
Arrow functions make our code more concise and increases the readability of the code, the new syntax is really easy to adopt and takes no time to understand things.
Apart from writing less and doing more Arrow Function can help us with
this keyword and scoping of variables, let me show you how.
Here in this above image I have made a class with 2 member functions, arrow and regular which consists of
setTimeout to make a block of code so that we can see the scope of
this keyword using arrow functions v/s regular function.
Here we will receive the name(Shreyas) and age(18) in the arrow function, as inside this function
thiskeyword will use the scope where it was created ( i.e. inside the class ) but on the other hand the regular function will use the scope where it is invoked or called i.e. which is outside the class and since there is no name and age defined outside the class, we will receive
One disadvantage I feel is, we can not use arrow function to define constructor.
A constructor is a special function which is to be made inside every class, which basically sets default values and initializes them.
In the above example you can see I have made a constructor function, but with normal function's syntax.
Thank you so much for reading the whole blog 🎉! I hope you learnt something and if you did, do implement it, it would make your code more concise and readable.