Middle
What is the difference between an arrow function and a regular function in JavaScript?
sobes.tech AI
Answer from AI
Main differences between arrow functions and regular functions in JavaScript:
-
thiscontext: Arrow functions do not have their ownthis. They inheritthisfrom the surrounding lexical context. Regular functions have their ownthis, which depends on how they are called. -
Lack of
arguments: Arrow functions do not have anargumentsobject. To access arguments, you need to use parameters or the rest operator. -
Cannot be used as constructors: Arrow functions cannot be called with
new. -
Syntax: Arrow functions are usually shorter and more convenient for concise expressions.
Example:
const obj = {
value: 42,
regularFunc: function() { return this.value; },
arrowFunc: () => this.value
};
console.log(obj.regularFunc()); // 42
console.log(obj.arrowFunc()); // undefined (this does not point to obj)