There are a few differences between regular functions and arrow functions in JavaScript:
1. Syntax: Arrow functions have a shorter syntax compared to regular functions. Arrow functions do not have the function keyword, and the return keyword is optional if the function body is a single expression.
function sum(a, b) {
return a + b;
}
const sum = (a, b) => a + b;
2. this keyword: The value of the this keyword inside a regular function is determined by how the function is called. In an arrow function, the value of this is inherited from the surrounding context.
const obj = {
name: 'John',
regularGreet: function() {
console.log(`Hello, my name is ${this.name}`);
},
arrowGreet: () => {
console.log(`Hello, my name is ${this.name}`);
}
};
obj.regularGreet();
obj.arrowGreet();
3. arguments object: The arguments object is an array-like object that is available inside functions. It can be used to access the arguments passed to the function. Arrow functions do not have their own arguments object. Instead, they can use the rest parameter syntax (...) to access the arguments passed to the function.
function sum() {
console.log(arguments);
}
const sum = () => {
console.log(arguments);
}
const sum = (...args) => {
console.log(args);
}
4.new operator: Regular functions can be called with the new operator to create an instance of an object. Arrow functions cannot be used as constructors and cannot be called with the new operator.
function Person(name) {
this.name = name;
}
const person = new Person('John');
console.log(person.name);
const Person = (name) => {
this.name = name;
}
const person = new Person('John');