Master three essential JavaScript patterns that elevate your code from functional to exceptional. Interactive examples included.
Transform functions with multiple arguments into a sequence of functions, each taking a single argument. This functional programming technique enables partial application and code reusability.
Fix arguments progressively for reusable function variants
Build complex logic from simple, testable functions
const multiply = (a) => (b) => (c) => a * b * c;
// Usage
const multiplyBy2 = multiply(2);
const multiplyBy2And3 = multiplyBy2(3);
multiplyBy2And3(4); // 24
Limit the rate at which a function can fire. Essential for performance optimization in scroll handlers, resize events, and API calls to prevent overwhelming the browser or server.
Reduce unnecessary calculations during rapid events
Protect APIs from excessive client requests
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
}
}
Represent the eventual completion (or failure) of an asynchronous operation and its resulting value. The foundation of modern asynchronous JavaScript programming.
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
success ? resolve('Data loaded!')
: reject('Error!');
}, 1000);
});
};
See how these concepts work together in a practical API request manager
const createAPIClient = (baseURL) => (authToken) => { // Curried configuration const headers = { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/json' }; // Throttled request function const throttledFetch = throttle(async (endpoint) => { const response = await fetch(`${baseURL}${endpoint}`, { headers }); return response.json(); }, 1000); return (endpoint) => new Promise((resolve) => { throttledFetch(endpoint).then(resolve); }); }; // Usage const api = createAPIClient('https://api.example.com')('token123');