Arrow functions in ECMAScript 6 should be utilized under the following conditions:
1. When this Binding is Needed:
Arrow functions inherit this from their surrounding lexical context, making them ideal for scenarios where maintaining the context is crucial.
Example:
class Example {
constructor(name) {
this.name = name;
}
printName() {
setTimeout(() => {
console.log(this.name); // 'this' refers to the class instance
}, 1000);
}
}
const ex = new Example('Edureka');
ex.printName(); // Output: Edureka
2. Shorter Syntax for Callbacks:
Arrow functions are useful for concise syntax in callback functions.
Example:
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]