Middle
How does an arrow function differ from a regular named function?
sobes.tech AI
Answer from AI
Arrow functions in JavaScript differ from regular named functions in several key aspects:
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.- Absence of
arguments: Arrow functions do not have anargumentsobject. To access arguments, you need to use parameters or rest parameters. - Cannot be used as constructors: Arrow functions cannot be invoked with
new. - Syntax: Arrow functions are shorter and more convenient for writing short functions.
Example:
const obj = {
value: 42,
regularFunc: function() { return this.value; },
arrowFunc: () => this.value
};
console.log(obj.regularFunc()); // 42
console.log(obj.arrowFunc()); // undefined, because `this` does not point to `obj`