Back to Tutorials
JavaScript ES6+ Features Tutorial
Lesson 1 of 5: Arrow Functions
Progress20%
Arrow Functions
Arrow functions are a concise way to write functions in JavaScript. They were introduced in ES6 and provide a shorter syntax compared to traditional function expressions.
Key features:
• Shorter syntax
• Lexical 'this' binding
• Cannot be used as constructors
• No 'arguments' object
• Implicit return for single expressions
Syntax comparison:
Traditional: function name() { return value; }
Arrow: () => value
When to use arrow functions:
• Array methods (map, filter, reduce)
• Event handlers
• Callback functions
• When you need lexical 'this' binding
When NOT to use:
• Object methods (use regular functions)
• Constructor functions
• When you need 'arguments' objectExample
// Traditional function
function multiply(a, b) {
return a * b;
}
// Arrow function
const multiply = (a, b) => a * b;
// Array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
// Event handlers
button.addEventListener('click', () => {
console.log('Button clicked!');
});
// Object methods (avoid arrow functions here)
const person = {
name: 'John',
greet: function() {
return `Hello, I'm ${this.name}`;
}
};Exercise
Convert the following traditional functions to arrow functions: 1. function add(a, b) { return a + b; } 2. function isEven(num) { if (num % 2 === 0) { return true; } else { return false; } } 3. const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 } ]; // Convert this filter function to arrow function const adults = users.filter(function(user) { return user.age >= 18; });
Lesson 1 of 5