In JavaScript, Function can be declared in different ways. The common way is to declare after using function keyword like below:
// Function declaration
function greetMessage(userName) {
return `Hello ${userName}`;
}
const greetMessage = (userName) => {
return `Hello ${userName}`;
}
What is the difference between Arrow Functions and Regular Functions?
1. Syntax
One very basic difference is that the Regular Functions uses function keyword but Arrow Functions don't inspite it uses arrow symbol(=>).
2. this keyword
Regular function have its their own this context, but the Arrow function don't have their own. Inside an Arrow function this value hold the this value of outer function.
let user = {
userName: "Parth",
greetMessage1:() => {
console.log("Hello " + this.userName); // Output: Hello undefined
},
greetMessage2(){
console.log("Good Morning " + this.userName); // Output: Good Morning Parth 'this' binding works here
}
};
user.greetMessage1();
user.greetMessage2();
In the above example, We can see the greetMessage1(Arrow Functions) don't have its own this, But the greetMessage2(Regular Function) have it's own this due to which we can see the userName value in output.
3. Using new keyword
Regular function are constructible and callable.As it are constructible, they can be called using the 'new' keyword. But the arrow functions are only callable and not constructible. Due to which we will get a run-time error when trying to construct a non-constructible arrow functions using the new keyword.
// With Regular functions
function sum(a, b) {
return a+b;
}
sum(10,20); // Outpu: 30
// With Arrow functions
const sum = (a, b) =>a+b;
sum(10,20); //Output: 30
Conclusion
In this article we saw the major differences between Arrow functions and Regular Functions which a JavaScript developer should know.
Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Thanks!