What is functional programming in JavaScript?
Detailed Explanation
Functional programming treats computation as evaluation of mathematical functions, avoiding state changes and mutable data.
Core Principles:
1. Pure Functions - same input, same output, no side effects
2. Immutability - data doesn't change
3. Higher-order Functions - functions that take/return functions
4. Function Composition - combining simple functions
Pure Functions:
// Pure
const add = (a, b) => a + b;// Impure (side effect)
let count = 0;
const increment = () => ++count;
Immutability:
// Instead of mutating
const addItem = (arr, item) => [...arr, item];// Instead of changing object
const updateUser = (user, updates) => ({ ...user, ...updates });
Higher-order Functions:
const numbers = [1, 2, 3, 4, 5];// map, filter, reduce are higher-order functions
const doubled = numbers.map(x => x * 2);
const evens = numbers.filter(x => x % 2 === 0);
const sum = numbers.reduce((acc, x) => acc + x, 0);
Function Composition:
const compose = (f, g) => x => f(g(x));const addOne = x => x + 1;
const double = x => x * 2;
const addOneThenDouble = compose(double, addOne);
console.log(addOneThenDouble(3)); // 8
Benefits:
- Predictable code
- Easier testing
- Better debugging
- Parallel processing
- Code reusability
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts