Functional Programming

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.

Illustration of Functional Programming
Illustration of Functional Programming

💡 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

JAVASCRIPT
function add(a, b) {
  return a + b; // no side effects
}
Output
add(2, 3) === 5

Immutability

Instead of modifying data, create new copies with changes. This avoids bugs related to shared state.

📌 Deep Dive: Immutability Example

JAVASCRIPT
const arr = [1, 2, 3];
// Instead of arr.push(4), create a new array:
const newArr = [...arr, 4];
Output
arr = [1, 2, 3]
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

JAVASCRIPT
const nums = [1, 2, 3];
const doubled = nums.map(x => x * 2);
Output
doubled = [2, 4, 6]

Function Composition

Combining small functions to build complex operations. This leads to clear, reusable, and testable code.

📌 Deep Dive: Function Composition Example

JAVASCRIPT
const add5 = x => x + 5;
const double = x => x * 2;

const add5ThenDouble = x => double(add5(x));

add5ThenDouble(3); // (3 + 5) * 2 = 16
Output
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.
Comparison: Imperative vs Functional Style
ImperativeFunctional
Uses loops and mutable variablesUses higher-order functions and immutability
Modifies state and dataUses pure functions without side effects
Focus on how to do tasks step-by-stepFocus 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.