๐งช Functional Programming = Clean Code
Imperative code is hard to maintain. Functional programming with array methods creates cleaner, more predictable code.
๐ Functional Patterns
// Pure Functions
const add = (a, b) => a + b; // Pure
const getTotal = (cart) => cart.reduce(add, 0); // Pure
// Higher-Order Functions
const map = (fn, arr) => arr.map(fn);
const filter = (fn, arr) => arr.filter(fn);
const reduce = (fn, initial, arr) => arr.reduce(fn, initial);
// Function Composition
const compose = (...fns) => (x) =>
fns.reduceRight((acc, fn) => fn(acc), x);
const pipe = (...fns) => (x) =>
fns.reduce((acc, fn) => fn(acc), x);
// Example: Data Pipeline
const processUsers = pipe(
(users) => users.filter(u => u.active),
(users) => users.map(u => ({ name: u.name, age: u.age })),
(users) => users.sort((a, b) => a.age - b.age),
(users) => users.reduce((acc, u) => {
acc[u.age] = (acc[u.age] || 0) + 1;
return acc;
}, {})
);
// Currying
const multiply = (a) => (b) => a * b;
const double = multiply(2);
const triple = multiply(3);
// Immutability
const updateUser = (user, updates) => ({
...user,
...updates
});
const addItem = (cart, item) => [...cart, item];
const removeItem = (cart, id) => cart.filter(item => item.id !== id);
๐ฏ Advanced Functional Programming
// Memoization
const memoize = (fn) => {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) {
cache.set(key, fn(...args));
}
return cache.get(key);
};
};
const expensiveFn = (n) => {
console.log('Computing...');
return n * n;
};
const memoizedFn = memoize(expensiveFn);
memoizedFn(5); // Computing...
memoizedFn(5); // From cache
// Lazy Evaluation
const lazy = (fn) => {
let computed = false;
let result = null;
return () => {
if (!computed) {
result = fn();
computed = true;
}
return result;
};
};
// Monad Pattern
const Maybe = (value) => ({
map: (fn) => Maybe(value !== null && value !== undefined ? fn(value) : null),
chain: (fn) => value !== null && value !== undefined ? fn(value) : Maybe(null),
get: () => value
});
// Functor Pattern
const map = (fn, functor) => functor.map(fn);
// Applicative Functor
const Applicative = (value) => ({
map: (fn) => Applicative(fn(value)),
apply: (functor) => Applicative(functor.get()(value)),
get: () => value
});
๐ก Functional Programming Tips
- Use pure functions
- Avoid side effects
- Use immutable data
- Compose functions
- Use higher-order functions
Functional programming makes your code more predictable and easier to test. It’s a powerful paradigm for modern JavaScript.

