Javascript functions can be written in many ways. The first and usual way is by just using the function
keyword:
Another way is by using the ES2015 way, which is called arrow function:
While both the regular function and arrow function works, have you ever wondered the difference in it and when to use it? I am going to show you the difference between the two and when to use the right syntax.
1. Variable Bindings
Arrow functions do not have variable binding. Though, they have access to the variable object that is closest non-arrow parent function. Below is an example of a regular function and arrow function.
Regular function:
Arrow Function:
2. THIS
Compared to regular functions, arrow function do not have their own this.
Because the value of this
inside an arrow function is the same throughout the lifecycle of the function. It is always connected to the value of this
in the non-arrow parent function. Shown below is an example.
3. NEW
Since regular function has the ability to be constructible, they can use the word new
keyword. However the arrow function are only callable and not constructible, arrow function cannot be used as a constructor function, which is why they cannot use the new
keyword. Example provided below.