Arrow Functions
Arrow functions provide a shorter syntax for writing functions and have different behavior with the this
keyword.
Basic Syntax
javascript// Traditional function function add(a, b) { return a + b; } // Arrow function const add = (a, b) => { return a + b; }; // Shorter arrow function (implicit return) const add = (a, b) => a + b; // Single parameter (parentheses optional) const square = x => x * x; const square = (x) => x * x; // Both are valid // No parameters const greet = () => "Hello!"; const getCurrentTime = () => new Date();
Different Arrow Function Forms
javascript// Multiple lines with explicit return const processUser = (user) => { const name = user.name.toUpperCase(); const age = user.age; return `${name} is ${age} years old`; }; // Single expression (implicit return) const double = x => x * 2; const isEven = num => num % 2 === 0; const getFullName = (first, last) => `${first} ${last}`; // Returning objects (wrap in parentheses) const createUser = (name, age) => ({ name: name, age: age, id: Math.random() }); // Array methods with arrow functions const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(x => x * 2); const evens = numbers.filter(x => x % 2 === 0); const sum = numbers.reduce((acc, x) => acc + x, 0);
Arrow Functions vs Regular Functions
javascript// 1. 'this' binding difference const obj = { name: "John", // Regular function - 'this' refers to obj regularMethod: function() { console.log("Regular:", this.name); // "John" }, // Arrow function - 'this' refers to outer scope arrowMethod: () => { console.log("Arrow:", this.name); // undefined (or global) } }; // 2. Cannot be used as constructors const RegularFunction = function(name) { this.name = name; }; const person1 = new RegularFunction("Alice"); // Works const ArrowFunction = (name) => { this.name = name; }; // const person2 = new ArrowFunction("Bob"); // Error! // 3. No arguments object function regularFunc() { console.log(arguments); // Works } const arrowFunc = () => { // console.log(arguments); // Error! // Use rest parameters instead }; const arrowWithRest = (...args) => { console.log(args); // Works };
Practical Examples
javascript// Array processing const users = [ { name: "Alice", age: 25, active: true }, { name: "Bob", age: 30, active: false }, { name: "Charlie", age: 35, active: true } ]; // Get active users const activeUsers = users.filter(user => user.active); // Get user names const userNames = users.map(user => user.name); // Find user by name const findUser = (name) => users.find(user => user.name === name); // Sort by age const sortedByAge = users.sort((a, b) => a.age - b.age); // Event handlers const button = document.querySelector("#myButton"); button?.addEventListener("click", () => { console.log("Button clicked!"); }); // API calls const fetchUser = async (id) => { const response = await fetch(`/api/users/${id}`); return response.json(); }; // Utility functions const isEmpty = arr => arr.length === 0; const isValidEmail = email => email.includes("@"); const formatPrice = price => `$${price.toFixed(2)}`; const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
When to Use Arrow Functions
javascript// ✅ Good for: Array methods const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(n => n * 2); const sum = numbers.reduce((acc, n) => acc + n, 0); // ✅ Good for: Short utility functions const add = (a, b) => a + b; const isPositive = x => x > 0; // ✅ Good for: Callbacks setTimeout(() => console.log("Timer finished"), 1000); // ❌ Avoid for: Object methods (when you need 'this') const user = { name: "John", greet: () => console.log(`Hello, ${this.name}`) // 'this' won't work }; // ✅ Better for object methods: const user = { name: "John", greet() { console.log(`Hello, ${this.name}`); // 'this' works correctly } }; // ❌ Avoid for: Event handlers that need 'this' button.addEventListener("click", () => { // 'this' doesn't refer to the button }); // ✅ Better: button.addEventListener("click", function() { // 'this' refers to the button });
Advanced Arrow Function Patterns
javascript// Immediately Invoked Arrow Function const result = ((x, y) => x + y)(5, 3); // 8 // Arrow functions in array methods chaining const processData = (data) => data .filter(item => item.active) .map(item => ({ ...item, processed: true })) .sort((a, b) => a.name.localeCompare(b.name)); // Conditional arrow functions const getStatus = (user) => user.isActive ? "online" : "offline"; const getDiscount = (user) => user.isPremium ? 0.2 : user.isRegular ? 0.1 : 0; // Arrow functions with destructuring const getFullName = ({ firstName, lastName }) => `${firstName} ${lastName}`; const calculateTotal = ({ price, quantity, tax = 0.1 }) => price * quantity * (1 + tax); // Currying with arrow functions const multiply = (a) => (b) => a * b; const double = multiply(2); const triple = multiply(3); console.log(double(5)); // 10 console.log(triple(4)); // 12