Introduction to Functional Programming: Pure Functions and Immutability

🚀 Introduction to Functional Programming (Part:1) Functional Programming is a programming style where we build applications using functions by avoiding changing data and state. Key Ideas of Functional Programming: ✔ Pure Functions:  Functions that always return the same output for the same input ✔ Immutability:  Do not change existing data, create new data instead ✔ First-Class Functions: Functions can be treated like variables ✔ Higher-Order Functions: Functions that take other functions as arguments What are Pure Functions? A pure function is a function that:  1. Always returns the same output for the same input  2. Has no side effects (does not change anything outside the function)  Example:(Pure Function) const add = (a, b) => {  return a + b; }; >> add(2, 3) will always return 5 >> It doesn’t modify any external data Example:1 (Not a Pure Function) let total = 0; const addToTotal = (num) => {  total += num; }; >> Output depends on previous value of total >> It modifies external state  Example:2 (Not Pure Function) const getRandom = () => {  return Math.random(); }; >> Same input → different output >> getRandom() = Unpredictable   Real-World Example 1: E-commerce Cart Total ❌ Not Pure (bad approach) let total = 0; const addToCart = (price) => {  total += price;}; ✅ Pure Function (good approach) const calculateTotal = (prices) => {  return prices.reduce((sum, price) => sum + price, 0);}; calculateTotal([100, 200, 300]);  // 600 >> Same input → same output >> No external changes >> Easy to test  Real-World Example 2: Updating User Data (React Style) ❌ Not Pure const user = { name: "Kavi", age: 21 }; const updateAge = () => {  user.age = 22; }; >> Problem: Directly mutating data (can cause UI bugs in React) ✅ Pure Function const updateAge = (user) => {  return { ...user, age: 22 }; }; const updatedUser = updateAge(user); >> Original object not changed >> Safe for React state updates  Real-World Example 3: Filtering Products ✅ Pure Function const filterExpensiveProducts = (products) => {  return products.filter(p => p.price > 1000); } filterExpensiveProducts([  { name: "Phone", price: 500 },  { name: "Laptop", price: 50000 } ]); >> No mutation >> Just transforms input → output 🔥 Where You’ll Use This >> React state updates >> API data transformation >> Redux / state management >> Data filtering & calculations #JavaScript #FunctionalProgramming #WebDevelopment #CleanCode #FrontendDevelopment #Coding #100DaysOfCode #DeveloperLife

To view or add a comment, sign in

Explore content categories