Arrow functions offer concise and efficient syntax for writing functions, making code cleaner and more readable while avoiding issues with 'this' binding.
Basic Arrow Function
const sayHello = () => { console.log("Hello!"); }; sayHello();
Arrow Function With a Single Parameter
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(num => num * 2); console.log(doubledNumbers); // [2, 4, 6, 8, 10]
Arrow Function With Multiple Parameters
const add = (a, b) => a + b; console.log(add(3, 4)); // Output: 7
Arrow function for Mapping an Array
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(num => num * 2); console.log(doubledNumbers); // [2, 4, 6, 8, 10]
Arrow Function for Filtering an Array
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4]
Arrow Function With an Implicit Return
const double = num => num * 2; console.log(double(6)); // Output: 12
Arrow Function as a Callback
const names = ["Alice", "Bob", "Charlie"]; const nameLengths = names.map(name => name.length); console.log(nameLengths); // Output: [5, 3, 7]
Arrow Function With a Default Parameter
const greet = (name = "Anonymous") => { console.log(`Hello, ${name}!`); }; greet(); // Output: Hello, Anonymous! greet("John"); // Output: Hello, John!
Arrow Function With Destructuring Parameters
const getFullName = ({ firstName, lastName }) => `${firstName} ${lastName}`; console.log(getFullName({ firstName: "John", lastName: "Doe" })); // Output: John Doe
Arrow Function Using The Rest Parameter
const sum = (...numbers) => numbers.reduce((acc, curr) => acc + curr); console.log(sum(1, 2, 3, 4, 5)); // Output: 15
Arrow Function With a Ternary Operator
const isEven = num => num % 2 === 0 ? "Even" : "Odd"; console.log(isEven(6)); // Output: Even console.log(isEven(7)); // Output: Odd
Arrow Function Used in setTimeout
setTimeout(() => { console.log("Delayed message"); }, 1000);
Arrow Function With a Conditional Statement
const getDiscountedPrice = (price, isPremiumMember) => { if (isPremiumMember) { return price * 0.8; } else { return price; } }; console.log(getDiscountedPrice(100, true)); // Output: 80 console.log(getDiscountedPrice(100, false)); // Output: 100
Top comments (0)