Day 45

Functional Programming

13 min
JavaScript 100 Days

Functional Programming (FP) ek programming paradigm hai jahan functions mathematical functions ki tarah behave karte hain. React, Redux sab FP principles use karte hain.

Core FP Concepts

Pure functions, immutability, aur higher-order functions.

fp.js
javascript
// Pure function — same input, same output, no side effects
function add(a, b) { return a + b; } // ✅ pure
let count = 0;
function impure() { count++; return count; } // ❌ impure — side effect

// Immutability — original change mat karo
const original = [1, 2, 3];
const added = [...original, 4]; // new array!
console.log(original); // [1, 2, 3] — unchanged

// Higher-order functions
function multiply(factor) {
  return (num) => num * factor; // returns function!
}

const double = multiply(2);
const triple = multiply(3);

console.log(double(5));  // 10
console.log(triple(5));  // 15

// Compose functions
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);

const addTax = price => price * 1.1;
const addShipping = price => price + 50;
const formatPrice = price => `Rs. ${price.toFixed(0)}`;

const getTotal = compose(formatPrice, addShipping, addTax);
console.log(getTotal(1000)); // Rs. 1150

🎯 Practice Challenge

3 pure functions banao: capitalize, reverseWords, removeSpecialChars. Compose karke ek single clean function banao.