91. Arrow Functions (ES6)
Arrow functions (=>) provide a concise syntax for writing function expressions. They are highly preferred in modern JS, especially for callbacks and array methods.
Concise Syntax
| Type | Syntax |
|---|---|
| Full | const add = function(a, b) { return a + b; } |
| Arrow Basic | const add = (a, b) => { return a + b; } |
| Single Parameter | const greet = name => { return 'Hi ' + name; } (Parentheses around name optional) |
| Implicit Return | const multiply = (a, b) => a * b; (Curly braces and return skipped if function is one expression) |
The this Difference (Crucial Concept)
Regular functions define their own this value based on how they are called. Arrow functions, however, do not bind their own this. Instead, they inherit the this value from the enclosing (lexical) scope.
This behavior makes them safer to use inside methods or event handlers, as this always reliably points to the containing object or window.
javascript const app = { name: 'App', start: function() { setTimeout(() => { // Arrow function inherits 'this' from 'start' method (which is 'app') console.log(this.name + ' started.'); }, 100); } }; app.start(); // Output: App started.