Arrow Functions vs. Traditional Functions in JavaScript
Harshit Pandey
React Native | JavaScript | Typescript | Android | IOS | DSA | Node JS
JavaScript provides two common ways to define functions: Arrow Functions and Traditional Functions. While both are useful, they have distinct differences that affect how they behave, particularly with this, arguments, and how they are used in different contexts.
1. Syntax Differences
Arrow Function
Arrow functions have a more concise syntax and are often used for short, one-line functions.
const add = (a, b) => a + b;
console.log(add(5, 3)); // Output: 8
Traditional Function
Traditional functions use the function keyword and can include function declarations or function expressions.
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8
2. this Keyword Behavior
Arrow Function
const obj = {
name: 'Harshit',
greet: function () {
const arrowGreet = () => console.log(`Hello, ${this.name}`);
arrowGreet();
},
};
obj.greet(); // Output: Hello, Harshit
Traditional Function
const obj = {
name: 'Harshit',
greet: function () {
function normalGreet() {
console.log(`Hello, ${this.name}`);
}
normalGreet();
},
};
obj.greet(); // Output: Hello, undefined (in strict mode)
Solution: Use .bind() or store this in a variable like self.
3. arguments Object
Arrow Function
function parentFunction() {
const arrowFunc = () => console.log(arguments);
arrowFunc(4, 5); // Uses parent arguments
}
parentFunction(1, 2, 3); // Output: [1, 2, 3]
Traditional Function
function normalFunc() {
console.log(arguments);
}
normalFunc(1, 2, 3); // Output: [1, 2, 3]
4. Use Cases: When to Use Which?
When to Use Arrow Functions
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
When to Use Traditional Functions
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log(`Hello, my name is ${this.name}`);
};
const harshit = new Person('Harshit');
harshit.greet(); // Output: Hello, my name is Harshit