Junior
What is an arrow function?
sobes.tech AI
Answer from AI
An arrow function is a more concise syntax for writing functions in JavaScript (ES6+).
Key features:
- Syntax:
(parameters) => expressionor{ function body }. this: Lexically bindsthis, meaning it takesthisfrom the surrounding context, not its own. This is the main difference from regular functions.- Absence of
arguments: Does not have its ownargumentsobject. You can use rest parameters (...args). - Absence of
prototype: Does not have aprototypeproperty and cannot be used as constructors (new). - Automatic
return: If the function body consists of a single expression, its result is implicitly returned (without thereturnkeyword).
Examples:
// Regular function
function sum(a, b) {
return a + b;
}
// Arrow function (short syntax)
const add = (a, b) => a + b;
// Arrow function with a code block
const multiply = (a, b) => {
const result = a * b;
return result;
};
Comparison of this:
class MyClass {
constructor() {
this.value = 10;
}
// Regular method - `this` refers to the MyClass instance
method() {
console.log(this.value); // 10
}
// Arrow function - `this` refers to the `this` from constructor (MyClass instance)
arrowMethod = () => {
console.log(this.value); // 10
}
callbackExample() {
// Regular function loses context of `this`
setTimeout(function() {
console.log(this); // Window or undefined in strict mode
}, 100);
// Arrow function preserves context of `this`
setTimeout(() => {
console.log(this.value); // 10
}, 100);
}
}