What are the features of arrow functions?
sobes.tech AI
Answer from AI
Features of arrow functions in JavaScript:
-
Lexical binding of
this: Arrow functions do not have their ownthiscontext; they inherit it from the surrounding scope. This is convenient for preserving context inside callbacks. -
Lack of
arguments: Arrow functions do not have their ownargumentsobject. To access arguments, you need to use parameters or rest parameters. -
Cannot be used as constructors: Arrow functions cannot be called with
new; they do not have an internal[[Construct]]method. -
No
prototype: Arrow functions do not have aprototypeproperty. -
Shorter syntax: If the function body consists of a single expression, you can omit the braces and
return.
Example:
const add = (a, b) => a + b;
const obj = {
value: 10,
increment: function() {
setTimeout(() => {
this.value++;
console.log(this.value); // `this` refers to `obj`
}, 1000);
}
};
obj.increment();
Here, the arrow function inside setTimeout inherits this from the increment method.