what are differences between normal function and arrow function in JS?
1. Syntax
Arrow functions are more concise, especially for single-line expressions.
// Normal function
function greet(name) {
return `Hello, ${name}`;
}
// Arrow function
const greet = (name) => `Hello, ${name}`;
2. this
Binding
Normal Functions:
- A normal function's this depends on how the function is called.
- In a method, this refers to the object the method is called on.
const obj = {
value: 10,
normalFunction() {
console.log(this.value); // `this` refers to obj
},
};
obj.normalFunction(); // 10
Arrow Functions:
Arrow functions do not have their own this
. They inherit this
from the enclosing scope at the time of definition.
const obj = {
value: 10,
arrowFunction: () => {
console.log(this.value); // `this` depends on the surrounding context, not obj
},
};
obj.arrowFunction(); // undefined (in strict mode), or window.value (in non-strict mode)
3. arguments
Object
Normal Functions:
- They have access to the
arguments
object, which holds all arguments passed to the function.
function normalFunction() {
console.log(arguments);
}
normalFunction(1, 2, 3); // [1, 2, 3]
Arrow Functions:
- Arrow functions do not have their own
arguments
. To access arguments, you must use rest parameters.
const arrowFunction = (...args) => {
console.log(args);
};
arrowFunction(1, 2, 3); // [1, 2, 3]
4. Constructors
Normal Functions:
- Can be used as constructors with the
new
keyword.
function Person(name) {
this.name = name;
}
const person = new Person("John");
console.log(person.name); // "John"
Arrow Functions:
- Cannot be used as constructors. Attempting to use
new
with an arrow function will throw an error.
5. Methods in Objects
Normal Functions:
- Ideal for defining methods in objects because they provide the correct
this
.
Arrow Functions:
- Arrow functions should not be used as methods in objects because
this
will not refer to the object.
6. Suitability for Callback Functions
Arrow functions are often preferred in callbacks where this
is not needed.
const numbers = [1, 2, 3];
const squares = numbers.map((n) => n * n);
console.log(squares); // [1, 4, 9]
Normal functions are useful in cases where this
is necessary in the callback.
const button = document.querySelector("button");
button.addEventListener("click", function () {
console.log(this); // `this` refers to the button
});
7. Performance
Normal functions and arrow functions generally have similar performance, but normal functions might have a slight overhead because of this
and arguments
binding.