Watch this on my Youtube Channel:
There are a few ways to declare a function in Javascript. Arrow function is the ES6 way to do so. But what are the benefits/differences of using an arrow function?
Let’s get started
Javascript has a long history dated back to 1995. Since then, many improvements were introduced. ES6 (aka EMCAScript6) was the Javascript released in 2015 that introduced the arrow function along with other great features.
Before you proceed, make sure you have a good understanding of how scoping works in JavaScript. I’ve covered this in my other blog post, feel free to check it out:
3 main ways to declare a function
There are 3 typical ways to declare a function in Javascript:
// method 1
function add(num1, num2){
return num1 + num2;
}// Note: method 1 is equivalent to the following (by default js uses the var keyword instead of let):var add = function(num1, num2){
return num1 + num2
}// method 2
let add = function(num1, num2){
return num1 + num2;
}// method 3 (the arrow function)
let add = (num1, num2) => {
return num1 + num2
}
First impression: the arrow function syntax is much cleaner isn’t it?
Now, let’s look at some examples.
Let’s say we have a clock object.
Traditionally we will need to bind the context to every closure we defined.
With arrow function, it automatically binds the context and lets our code looks cleaner!
In short:
function(){
//.....
}.bind(this)// is equivalent to() => {
// ....
}
Key takeaway
- Arrow function always binds “this” to the current context.
- Arrow function is a cleaner way to write functions.
- Arrow function is by no means to replace the traditional function.