Arrow Syntax
Arrow Syntax
Basic Syntax
// Traditional
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => {
return a + b;
};
One Parameter
// Parentheses optional for single parameter
const square = x => x * x;
const square2 = (x) => x * x; // Also valid
No Parameters
// Parentheses required
const sayHello = () => 'Hello!';
Implicit Return
// Single expression: implicit return
const double = x => x * 2;
// Multi-line: explicit return needed
const process = (x) => {
const result = x * 2;
return result;
};
Returning Objects
// Must wrap in parentheses
const createUser = (name, age) => ({ name, age });
// Without parentheses (wrong)
const createUser2 = (name, age) => { name, age }; // undefined
Arrow Functions with Arrays
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const sum = numbers.reduce((a, b) => a + b, 0);
const evens = numbers.filter(n => n % 2 === 0);
Lexical this
Lexical this
The Problem with Regular Functions
const person = {
name: 'John',
greet: function() {
setTimeout(function() {
console.log(`Hello, ${this.name}`); // undefined!
}, 1000);
}
};
person.greet(); // "Hello, undefined"
Arrow Functions Fix This
const person = {
name: 'John',
greet: function() {
setTimeout(() => {
console.log(`Hello, ${this.name}`); // "John"
}, 1000);
}
};
person.greet(); // "Hello, John"
How Lexical This Works
// Arrow function inherits 'this' from enclosing scope
const person = {
name: 'John',
greet: () => {
// 'this' is NOT person (it's the outer scope)
console.log(this.name); // undefined
}
};
// Use regular method for object context
const person2 = {
name: 'John',
greet() {
console.log(this.name); // "John"
}
};
Class Example
class Timer {
constructor() {
this.seconds = 0;
}
start() {
// Arrow function inherits 'this' from class
this.interval = setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
stop() {
clearInterval(this.interval);
}
}
Callback Example
// Before ES6
const button = document.querySelector('button');
button.addEventListener('click', function() {
this.classList.add('active');
});
// With arrow function (wrong for event handlers)
button.addEventListener('click', () => {
this.classList.add('active'); // 'this' is not the button!
});
// Arrow functions in array methods (correct)
const numbers = [1, 2, 3];
numbers.map(n => n * 2); // Good
When to Use
When to Use
Use Arrow Functions For
// Array methods
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
// Callbacks with lexical this
setTimeout(() => console.log('done'), 1000);
// Promise chains
fetch(url)
.then(res => res.json())
.then(data => console.log(data));
// Functional programming
const compose = (f, g) => x => f(g(x));
Don't Use Arrow Functions For
// Object methods (when you need 'this')
const obj = {
name: 'John',
greet() { // Good
console.log(this.name);
},
greet: () => { // Bad
console.log(this.name); // undefined
}
};
// Event handlers (when you need the element)
button.addEventListener('click', function() {
this.classList.add('active'); // Good
});
// Constructors
class User {
constructor(name) {
this.name = name;
}
}
// Prototypes
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hi, ${this.name}`;
};
Summary
| Use Arrow | Don't Use Arrow |
|---|---|
| Array methods | Object methods |
| Callbacks | Event handlers |
| Promises | Constructors |
| Functional programming | Prototype methods |
Arrow Functions as Arguments
// Good pattern
function fetchData(callback) {
const data = getData();
callback(data);
}
fetchData(data => console.log(data));
Practice Problems
Create a reusable React component implementing Arrow Functions. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Arrow Functions using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Arrow Functions for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is the syntax for an arrow function with no parameters?
2. How do arrow functions handle 'this'?
3. When should you NOT use arrow functions?
4. How do you return an object literal from an arrow function?
5. What is the implicit return?
Flashcards
Question
What is the arrow function syntax?
Click to reveal answer
Answer
const fn = (params) => expression; or const fn = (params) => { statements; }
Question
How does 'this' work in arrow functions?
Click to reveal answer
Answer
Arrow functions inherit 'this' from the enclosing scope (lexical this).
Question
When should you avoid arrow functions?
Click to reveal answer
Answer
For object methods, event handlers, and constructors that need their own 'this'.
Question
How do you return an object from an arrow function?
Click to reveal answer
Answer
Wrap the object in parentheses: () => ({ key: value }).
Question
What is implicit return?
Click to reveal answer
Answer
When an arrow function automatically returns the expression without using the return keyword.
Revision Notes
Key Takeaways
- 1.Arrow functions provide shorter syntax
- 2.They inherit 'this' from enclosing scope
- 3.Use parentheses for no parameters
- 4.Wrap object returns in parentheses
- 5.Don't use for object methods needing 'this'
Interview Tips
- •Explain lexical this in arrow functions
- •Know when to use vs avoid arrow functions
- •Understand the syntax variations
- •Be able to refactor callbacks to arrow functions
Cheat Sheet
Arrow Functions Cheat Sheet
Syntax
// Basic
const add = (a, b) => a + b;
// No params
const greet = () => 'Hello';
// One param
const square = x => x * x;
// Multi-line
const process = (x) => {
const result = x * 2;
return result;
};
// Return object
const createUser = (name) => ({ name });
Lexical This
// Arrow: inherits this
const obj = {
name: 'John',
greet: () => {
console.log(this.name); // undefined
}
};
// Regular: own this
const obj = {
name: 'John',
greet() {
console.log(this.name); // 'John'
}
};
When to Use
- Array methods (map, filter, reduce)
- Callbacks
- Promise chains
- Functional programming