JavaScript Arrow Functions
Arrow functions provide a shorter syntax for functions and unique this behavior.
What Are Arrow Functions?
A concise way to write function expressions:
// Traditional
let greet = function(name) {
return `Hello, ${name}!`;
};
// Arrow
let greet = (name) => `Hello, ${name}!`;
Syntax Variations
// One parameter — parentheses optional
let double = x => x * 2;
// Multiple parameters — parentheses required
let add = (a, b) => a + b;
// Multiple statements — braces + explicit return
let complex = (x) => {
let result = x * 2;
return result;
};
Remember: Single expression = implicit return. Multiple statements = use {} and return.
No this Binding
Arrow functions inherit this from the outer scope:
let person = {
name: "John",
greet() {
console.log(`Hello, I'm ${this.name}`); // "John"
},
greetArrow: () => {
console.log(`Hello, I'm ${this.name}`); // undefined
}
};
Tip: Never use arrow functions as object methods — this won’t point to the object.
Arrow Functions in Callbacks
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map((n) => n * 2);
let evens = numbers.filter((n) => n % 2 === 0);
Complete Example: Filter and Transform
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 17 },
{ name: "Charlie", age: 30 }
];
let adults = users.filter((user) => user.age >= 18);
let names = adults.map((user) => user.name.toUpperCase());
console.log(names); // ["ALICE", "CHARLIE"]
Promise Handling
fetchData("https://api.example.com")
.then((data) => console.log(data))
.catch((error) => console.log(error));
Best Practices
- Use for callbacks — cleaner syntax
- Use regular functions for methods — so
thisworks - Use implicit return for simple functions — more concise
Common Mistakes
- Using arrow functions as object methods —
thisis wrong - Using arrow functions as constructors — they can’t be used with
new - Using
argumentsobject — arrow functions don’t have it - Forgetting parentheses with multiple parameters — syntax error