Functional Programming (FP) is a programming style that treats computation as the evaluation of mathematical functions, avoiding changing state and mutable data. In JavaScript, FP encourages writing pure functions, using higher-order functions, and focusing on immutability.

💡 Core Principles of Functional Programming
- Pure Functions: Output depends only on input, no side-effects.
- Immutability: Data cannot be changed once created.
- First-Class and Higher-Order Functions: Functions treated as values and passed around.
- Function Composition: Building complex functions by combining simpler ones.
Pure Functions
Pure functions always return the same output for the same input and do not modify external state.
📌 Deep Dive: Pure Function Example
function add(a, b) {
return a + b; // no side effects
}
Immutability
Instead of modifying data, create new copies with changes. This avoids bugs related to shared state.
📌 Deep Dive: Immutability Example
const arr = [1, 2, 3];
// Instead of arr.push(4), create a new array:
const newArr = [...arr, 4];
newArr = [1, 2, 3, 4]
Higher-Order Functions
Functions that take other functions as arguments or return them. Common in JavaScript: map, filter, reduce.
📌 Deep Dive: Using map
const nums = [1, 2, 3];
const doubled = nums.map(x => x * 2);
Function Composition
Combining small functions to build complex operations. This leads to clear, reusable, and testable code.
📌 Deep Dive: Function Composition Example
const add5 = x => x + 5;
const double = x => x * 2;
const add5ThenDouble = x => double(add5(x));
add5ThenDouble(3); // (3 + 5) * 2 = 16
💡 Benefits of Functional Programming
- Easier to reason about code due to pure functions.
- Improved testability and debugging.
- Reduced side-effects and bugs.
- Clear data transformations using functions like map, filter, reduce.
| Imperative | Functional |
|---|---|
| Uses loops and mutable variables | Uses higher-order functions and immutability |
| Modifies state and data | Uses pure functions without side effects |
| Focus on how to do tasks step-by-step | Focus on what to compute and transformation |
⚠️ Avoid Side Effects in Functional Code
Side effects like modifying external variables or performing I/O inside functions make reasoning harder. Keep functions pure for predictable behavior.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What best describes a pure function?
Question 2 of 2
Which JavaScript method is commonly used for functional transformations on arrays?
Loading results...