Arrow Functions
Arrow Functions
Section titled “Arrow Functions”What it is
Section titled “What it is”Arrow functions provide a shorter syntax for writing functions and lexically bind the this value. Introduced in ES6 (2015), they’re ideal for callbacks and short functions.
Before this feature
Section titled “Before this feature”Traditional function expressions were verbose and had issues with this:
// Verbose syntaxconst numbers = [1, 2, 3];const doubled = numbers.map(function(n) { return n * 2;});
// 'this' binding issuesfunction Timer() { this.seconds = 0;
// 'this' is lost in callback setInterval(function() { this.seconds++; // 'this' is undefined or window! }, 1000);
// Workaround: save 'this' const self = this; setInterval(function() { self.seconds++; }, 1000);}After this feature
Section titled “After this feature”Arrow functions provide concise syntax and fix this binding:
// Concise syntaxconst doubled = numbers.map(n => n * 2);
// Multiple parametersconst add = (a, b) => a + b;
// No parametersconst getRandom = () => Math.random();
// Block body (explicit return)const greet = name => { const message = `Hello, ${name}!`; return message;};
// Lexical 'this'function Timer() { this.seconds = 0;
// 'this' refers to Timer instance setInterval(() => { this.seconds++; }, 1000);}
// Object literals (must wrap in parentheses)const createUser = (name, age) => ({ name, age });
// Array methodsconst users = [ { name: "Alice", age: 25 }, { name: "Bob", age: 30 }];
const names = users.map(u => u.name);const adults = users.filter(u => u.age >= 18);const totalAge = users.reduce((sum, u) => sum + u.age, 0);Why this is better
Section titled “Why this is better”- Concise: Shorter syntax, especially for one-liners
- Lexical this:
thisfrom enclosing scope (no moreself = this) - Implicit return: Single expressions return automatically
- Readable: Great for functional programming patterns
- No binding: Can’t use
call(),apply(), orbind()to changethis
Key notes / edge cases
Section titled “Key notes / edge cases”- Can’t be used as constructors (no
new) - No
argumentsobject (use rest parameters instead) - Can’t be used as methods if you need
thisto refer to object - Must wrap object literals in parentheses
- Single parameter doesn’t need parentheses
- Always anonymous (can’t name them)
// Can't use as constructorconst Person = (name) => { this.name = name };const alice = new Person("Alice"); // TypeError!
// No arguments objectconst sum = () => { console.log(arguments); // ReferenceError!};// Use rest insteadconst sum2 = (...args) => args.reduce((a, b) => a + b);
// Method definition caveatconst obj = { count: 10, // BAD - arrow function increment: () => { this.count++; // 'this' is NOT obj! }, // GOOD - regular method decrement() { this.count--; }};
// Wrap object literalsconst makeUser = name => { name: name }; // ERROR! thinks it's a blockconst makeUser2 = name => ({ name: name }); // CorrectQuick practice
Section titled “Quick practice”-
Convert to arrow function:
function double(x) { return x * 2; }Answer
const double = x => x * 2;// orconst double = (x) => x * 2; -
Filter even numbers from
[1, 2, 3, 4, 5, 6]using arrow functionAnswer
const evens = [1, 2, 3, 4, 5, 6].filter(n => n % 2 === 0); -
Why can’t arrow functions be used as constructors?
Answer
Arrow functions don't have their own `this` binding and can't be called with `new`. They inherit `this` from the enclosing scope.