📘 Functional Programming – Beginner Friendly Guide
🌱 1. What is Functional Programming?
Functional Programming is a way of writing code where:
We treat functions as the main building blocks
We avoid changing data
We focus on “what to do” instead of “how to do it”
👉 Think of it like math:
f(x) = x + 2
Same input → same output, always.
🤔 Why Functional Programming?
Functional programming helps us:
Write clean and readable code
Avoid bugs caused by changing data
Make code easy to test
Handle modern features like React, Redux, [Link] better
🧠 2. Core Idea of Functional Programming
FP is built on 5 main pillars:
1. Functions are first-class citizens
2. Pure functions
3. Immutability
4. Higher-order functions
5. Function composition
We’ll learn each one slowly.
🧩 3. Functions as First-Class Citizens
What does this mean?
In JavaScript, functions can be:
Stored in variables
Passed as arguments
Returned from other functions
Example:
const greet = function(name) {
return "Hello " + name;
};
[Link](greet("Prachi"));
✔ Here, a function is treated like a value.
🔁 Function passed as argument
function sayHello(fn) {
[Link](fn("Prachi"));
sayHello(greet);
💡 This is very important in Functional Programming.
🧪 4. Pure Functions (MOST IMPORTANT)
What is a Pure Function?
A function is pure if:
1. Same input → same output
2. It does not change anything outside
❌ Impure Function
let count = 0;
function increment() {
count++;
❌ Changes external variable
✅ Pure Function
function increment(count) {
return count + 1;
✔ No side effects
✔ Predictable
✔ Easy to test
🧠 Real-Life Analogy
🍳 Pure Function = Recipe
Same ingredients → same dish
🧪 Impure Function = Cooking while someone keeps changing ingredients
🔒 5. Immutability (Do NOT change data)
Meaning:
Once data is created, don’t change it.
Instead, create a new copy.
❌ Mutable (Bad FP)
let arr = [1, 2, 3];
[Link](4);
✅ Immutable (Good FP)
let arr = [1, 2, 3];
let newArr = [...arr, 4];
✔ Original data is safe
✔ Fewer bugs
🧠 6. Higher-Order Functions (Very Powerful)
Definition:
A higher-order function:
Takes a function as argument OR
Returns a function
Example: map()
let numbers = [1, 2, 3];
let doubled = [Link](function(n) {
return n * 2;
});
[Link](doubled);
✔ No loops
✔ No mutation
✔ Clean logic
Other common higher-order functions:
map() → transform data
filter() → select data
reduce() → combine data
🔍 Example: filter()
let nums = [1, 2, 3, 4, 5];
let evenNums = [Link](n => n % 2 === 0);
[Link](evenNums);
🧮 Example: reduce()
let nums = [1, 2, 3, 4];
let sum = [Link]((total, n) => total + n, 0);
[Link](sum);
🔗 7. Function Composition
Meaning:
Combine small functions to create bigger logic.
Example:
const add2 = x => x + 2;
const multiply3 = x => x * 3;
const result = multiply3(add2(5));
[Link](result); // 21
✔ Small
✔ Reusable
✔ Clean
🧠 FP Mindset (Very Important)
Instead of:
“Change this variable again and again”
Think:
“Create new values using functions”
📝 Summary (Exam / Interview Ready)
✔ Functional Programming focuses on pure functions
✔ Avoids changing data (immutability)
✔ Uses higher-order functions
✔ Makes code clean, predictable, and reusablePerfect 👍
Let’s continue like a real classroom lesson.
Today’s Lesson 2 is very important conceptually.
📘 Functional Programming – Lesson 2
🔍 Pure vs Impure Functions + FP vs OOP (Beginner Friendly)
🧪 PART 1: Pure vs Impure Functions (DEEP UNDERSTANDING)
✅ What is a Pure Function?
A function is pure when:
✔ Rule 1: Same input → Same output
✔ Rule 2: No side effects
🧠 Side Effects mean:
Changing global variables
Modifying objects or arrays
Printing to console
Making API calls
Reading/writing files
✅ Pure Function Example
function add(a, b) {
return a + b;
}
✔ Predictable
✔ Testable
✔ Safe
❌ Impure Function Example
let taxRate = 0.18;
function calculateTax(amount) {
return amount + amount * taxRate;
❌ Depends on external variable
❌ Output may change
✅ Make it Pure
function calculateTax(amount, taxRate) {
return amount + amount * taxRate;
🧠 Real-Life Analogy
Pure Function Impure Function
Calculator Weather
Math Formula News
Recipe Kitchen with people interfering
🧼 Why Pure Functions are Loved in FP?
Easy debugging
Easy unit testing
Safe for parallel execution
Used heavily in React, Redux
⚔️PART 2: Functional Programming vs OOP
Let’s compare thinking style, not just syntax.
🧠 Thinking Difference
OOP asks:
What objects exist?
What can they do?
FP asks:
What transformations happen to data?
📊 FP vs OOP (Exam-Ready Table)
Basis Functional Programming Object-Oriented Programming
Main focus Functions Objects
Basis Functional Programming Object-Oriented Programming
Data Immutable Mutable
State Avoided Stored inside objects
Side effects Avoided Common
Style Declarative Imperative
Examples React, Redux Java, C++, Python
🧩 Example: Same Task in OOP vs FP
🔴 OOP Style
class Counter {
constructor() {
[Link] = 0;
increment() {
[Link]++;
let c = new Counter();
[Link]();
❌ State changes
🟢 Functional Style
function increment(count) {
return count + 1;
let count = 0;
count = increment(count);
✔ No hidden state
✔ Predictable
🧠 FP is NOT Against OOP
👉 Modern JavaScript uses both together
Example: React uses FP heavily inside OOP-like components.
🎯 PART 3: Declarative vs Imperative Style
❌ Imperative (HOW)
let result = [];
for (let i = 0; i < [Link]; i++) {
[Link](numbers[i] * 2);
✅ Declarative (WHAT)
let result = [Link](n => n * 2);
✔ Cleaner
✔ Less error-prone
✔ FP-style
🧠 Golden FP Rules (Write & Remember)
✦ Avoid shared state
✦ Use pure functions
✦ Prefer map, filter, reduce
✦ Don’t modify data
✦ Small functions → big logic
📝 Practice (Teacher Task 🧑🏫)
Task 1:
Is this function pure or impure? Why?
let bonus = 500;
function salary(total) {
return total + bonus;
Task 2:
Convert this into functional style:
let nums = [1, 2, 3, 4];
let sum = 0;
for (let i = 0; i < [Link]; i++) {
sum += nums[i];
Reply with your answers.
Next Lesson 👉 Higher-Order Functions (map, filter, reduce) MASTERCLASS with patterns 🔥
🎯 Your Practice Task (Very Easy)
Try this yourself:
1. Write a pure function that:
o Takes an array
o Returns only numbers greater than 10
2. Do NOT use loops (for, while)
Send me your answer, and I’ll correct it like a teacher 😊
Next lesson: Pure vs Impure (Deeply) + FP vs OOP comparison
Excellent 👍
Welcome to Lesson 3 — this is where Functional Programming becomes powerful and practical.
📘 Functional Programming – Lesson 3
🚀 Higher-Order Functions: map, filter, reduce (MASTERCLASS)
🧠 Quick Recall (1 minute)
✔ Function can be passed as data
✔ Functions can return functions
✔ This gives us Higher-Order Functions (HOFs)
🔁 What is a Higher-Order Function?
A function that:
Takes another function as input, OR
Returns a function
🟢 Real-Life Analogy
📦 Factory Machine
Input: raw material + instructions
Output: finished product
HOF = machine
Callback = instruction
🧩 1️⃣ map() – Transform Data
Purpose:
👉 Change each element without changing array length
Syntax:
[Link]((element) => newElement)
Example 1: Double numbers
let nums = [1, 2, 3];
let doubled = [Link](n => n * 2);
[Link](doubled); // [2, 4, 6]
✔ No loop
✔ No mutation
✔ Clean logic
Example 2: Extract property
let users = [
{ name: "Prachi", age: 21 },
{ name: "Riya", age: 22 }
];
let names = [Link](user => [Link]);
[Link](names);
🧩 2️⃣ filter() – Select Data
Purpose:
👉 Keep only elements that satisfy a condition
Syntax:
[Link]((element) => true / false)
Example 1: Even numbers
let nums = [1, 2, 3, 4, 5];
let even = [Link](n => n % 2 === 0);
[Link](even);
Example 2: Age above 18
let users = [
{ name: "A", age: 17 },
{ name: "B", age: 20 }
];
let adults = [Link](user => [Link] >= 18);
🧩 3️⃣ reduce() – Combine Data (MOST IMPORTANT)
Purpose:
👉 Reduce multiple values into one value
Syntax:
[Link]((accumulator, current) => newAcc, initialValue)
Example 1: Sum
let nums = [1, 2, 3, 4];
let sum = [Link]((total, n) => total + n, 0);
[Link](sum);
Example 2: Product
let product = [Link]((p, n) => p * n, 1);
Example 3: Count items
let fruits = ["apple", "banana", "apple"];
let count = [Link]((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
🧠 How to Think in reduce()
Name Meaning
accumulator Result so far
current Current item
initialValue Starting point
🔗 Combining map + filter + reduce (REAL FP)
Problem:
👉 Sum of even numbers only
let nums = [1, 2, 3, 4, 5];
let result = nums
.filter(n => n % 2 === 0)
.map(n => n * 2)
.reduce((sum, n) => sum + n, 0)
[Link](result);
✔ Declarative
✔ Readable
✔ Powerful
🧠 FP Pattern to Remember
❌ Loop → if → push → update
✅ filter → map → reduce
📌 Common Mistakes Beginners Make
❌ Modifying array inside map
❌ Using map when filter needed
❌ Fear of reduce 😄
👉 Reduce is just smart accumulation
📝 Teacher Practice (Important)
Task 1:
From this array:
let nums = [5, 10, 15, 20];
👉 Get sum of numbers greater than 10 using FP style.
Task 2:
Convert this to FP:
let users = [
{ name: "A", salary: 20000 },
{ name: "B", salary: 30000 }
];
let total = 0;
for (let i = 0; i < [Link]; i++) {
total += users[i].salary;
Reply with your answers 💬
Next Lesson 👉 Immutability + Why FP makes React easier ⚛️
Great consistency, Prachi 👏
Welcome to Lesson 4 — this lesson explains why Functional Programming is so powerful in real projects (especially
React).
📘 Functional Programming – Lesson 4
🔒 Immutability + State Thinking (VERY IMPORTANT)
🧠 What is Immutability?
Immutability means:
Once data is created, do NOT change it
Instead:
Create new data from old data
❌ Mutable (Non-FP Thinking)
let user = { name: "Prachi", age: 21 };
[Link] = 22; // ❌ data changed
❌ Hard to track
❌ Causes bugs in big apps
✅ Immutable (FP Thinking)
let user = { name: "Prachi", age: 21 };
let updatedUser = {
...user,
age: 22
};
✔ Original safe
✔ Easy debugging
🧠 Why Mutability is Dangerous?
Imagine:
5 functions using same object
One function silently changes it
Other functions break 😵
Immutability = data safety lock 🔐
🧩 Immutability with Arrays
❌ Mutable Methods
push()
pop()
splice()
sort()
✅ Immutable Alternatives
// add
let newArr = [...arr, 5];
// remove
let filtered = [Link](n => n !== 3);
// update
let updated = [Link](n => n === 2 ? 20 : n);
🧠 Real-Life Analogy
📄 Google Docs history
You don’t overwrite — you create versions
⚛️Why React LOVES Immutability
React checks:
“Has data changed?”
If you mutate:
[Link]++;
❌ React may NOT re-render
If you replace:
setCount(count + 1);
✔ React re-renders correctly
🔁 State as a Snapshot (FP Mindset)
State is NOT:
something you modify
State IS:
a new snapshot every time
🧩 Example: Counter (FP Style)
function reducer(state, action) {
if (action === "INCREMENT") {
return { count: [Link] + 1 };
return state;
}
✔ No mutation
✔ Predictable
✔ Redux-style FP
🧠 Benefits of Immutability
✔ Easy undo/redo
✔ Time travel debugging
✔ Safer concurrency
✔ Easier testing
🎯 FP + Immutability Pattern
Old State → Pure Function → New State
📝 Teacher Practice
Task 1:
Convert this to immutable:
let cart = [100, 200];
[Link](300);
Task 2:
Update age of user immutably:
let user = { name: "A", age: 25 };
👉 change age to 26
Reply with your answers 💬
Next Lesson 👉 Function Composition + Currying (FP Superpowers) 🔥
Excellent progress, Prachi 🌟
Welcome to Lesson 5 — this is where you move from using FP to thinking in FP.
📘 Functional Programming – Lesson 5
🔗 Function Composition & 🍛 Currying (FP Superpowers)
🔗 PART 1: Function Composition
📌 Meaning
Function Composition means:
Combining small functions to build complex logic
Just like math:
f(g(x))
🧠 Why Composition?
✔ Small functions
✔ Reusable
✔ Easy testing
✔ Clean code
🧩 Simple Example
const add2 = x => x + 2;
const multiply3 = x => x * 3;
const result = multiply3(add2(4));
[Link](result); // 18
🧠 Real-Life Analogy
🧼 Washing Machine
Wash → Rinse → Dry
Each step = function
🛠 Create a compose Function
const compose = (f, g) => x => f(g(x));
const add2 = x => x + 2;
const square = x => x * x;
const composed = compose(square, add2);
[Link](composed(3)); // 25
🔄 Multiple Functions Composition
const composeMany = (...fns) =>
x => [Link]((v, f) => f(v), x);
🍛 PART 2: Currying
📌 Meaning
Currying converts:
A function with multiple arguments
➡️Into a chain of single-argument functions
🧩 Normal Function
function add(a, b) {
return a + b;
🧩 Curried Function
const add = a => b => a + b;
const add5 = add(5);
[Link](add5(3)); // 8
🧠 Why Currying is Useful?
✔ Reusability
✔ Partial application
✔ Cleaner composition
✔ Used in React & Redux
🧩 Practical Example
const discount = rate => price => price - price * rate;
const tenPercentOff = discount(0.10);
[Link](tenPercentOff(500)); // 450
🧠 Currying + Composition (POWER MOVE)
const multiply = a => b => a * b;
const add = a => b => a + b;
const add2 = add(2);
const multiply3 = multiply(3);
const result = multiply3(add2(5));
[Link](result); // 21
📌 FP Thinking Pattern
❌ Big function doing everything
✅ Small functions combined together
🚫 Common Beginner Confusions
❓ “Why not normal functions?”
👉 FP focuses on flexibility & reuse
❓ “Is currying compulsory?”
👉 No, but it’s a power tool
📝 Teacher Practice (Very Important)
Task 1:
Create a curried function:
multiply(a, b)
Task 2:
Compose two functions:
Convert number to double
Then subtract 1
Reply with your solutions 💬
Next Lesson 👉 FP in Real Life: React, Redux & Interview Patterns ⚛️🔥
Wonderful, Prachi 👏
You’ve reached the final core lesson of Functional Programming.
This one connects theory → real-world → interviews.
📘 Functional Programming – Lesson 6
⚛️FP in Real Life: React, Redux & Interview Patterns
🧠 Why Companies Love Functional Programming
✔ Predictable behavior
✔ Easy debugging
✔ Less bugs
✔ Perfect for UI state management
✔ Scales well in large applications
That’s why FP is used in:
React
Redux
Modern JavaScript
Backend APIs
⚛️FP in React (VERY IMPORTANT)
🧩 React is FP-heavy
React components are basically:
Pure functions of props & state
❌ Bad (Impure Thinking)
function Counter() {
let count = 0;
count++;
return <h1>{count}</h1>;
❌ React breaks
❌ Not predictable
✅ Good (FP Thinking)
function Counter({ count }) {
return <h1>{count}</h1>;
✔ Pure component
✔ Same props → same UI
🔁 State Update (Immutability)
setUsers(prevUsers => [...prevUsers, newUser]);
✔ FP-style
✔ Safe update
🧠 Redux = Pure Functions (Reducers)
Reducer Rules:
✔ Pure function
✔ No mutation
✔ Same state + action → same new state
Example Reducer
function counterReducer(state = { count: 0 }, action) {
switch ([Link]) {
case "INC":
return { count: [Link] + 1 };
default:
return state;
🧠 FP Interview Questions (MUST KNOW)
Q1️⃣ What is Functional Programming?
✔ Programming paradigm
✔ Based on pure functions
✔ Avoids shared state & mutation
✔ Uses higher-order functions
Q2️⃣ What are side effects?
✔ Any change outside function
✔ Modifying variables
✔ API calls
✔ Console logs
Q3️⃣ Why immutability?
✔ Predictability
✔ Easier debugging
✔ Safe concurrency
✔ React performance
Q4️⃣ Difference between map, filter, reduce?
Method Purpose
map Transform
filter Select
reduce Combine
🧩 Common FP Coding Patterns (INTERVIEW)
1️⃣ Remove duplicates
let unique = arr => [...new Set(arr)];
2️⃣ Count occurrences
let count = arr =>
[Link]((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
3️⃣ Sum of even numbers
let sumEven = arr =>
[Link](n => n % 2 === 0)
.reduce((a, b) => a + b, 0);
🧠 FP Mindset (FINAL TAKEAWAY)
Think in data flow, not state changes:
Input → Pure Functions → Output
🏁 Functional Programming Roadmap (You Completed!)
✔ Basics
✔ Pure functions
✔ Immutability
✔ Higher-order functions
✔ Composition
✔ Currying
✔ Real-world usage
👏👏👏
🎯 Final Teacher Challenge (Optional but Powerful)
👉 Build a small FP program:
Take an array of numbers
Remove negatives
Double values
Find total sum
👉 Use ONLY:
map, filter, reduce
If you want, next we can:
1️⃣ Practice 50 FP coding questions
2️⃣ Learn Advanced FP (Monads, Lazy evaluation)
3️⃣ Learn FP patterns for React interviews
4️⃣ Switch to OOP vs FP deep coding comparison
Just tell me 💬
Excellent choice, Prachi 🔥
Here are 50 Functional Programming coding questions, arranged from easy → advanced, interview-oriented, and
JavaScript-focused.
👉 Rule for practice:
✔ No for / while loops
✔ Prefer map, filter, reduce
✔ Avoid mutation
🧠 50 Functional Programming Coding Questions (JS)
🟢 LEVEL 1: Beginner (1–15)
1. Double each number in an array
2. Convert all strings to uppercase
3. Get only even numbers from an array
4. Find length of each string in an array
5. Add 5 to every number
6. Extract only names from an array of objects
7. Check if all numbers are positive
8. Check if at least one number is negative
9. Convert array of numbers to strings
10. Find sum of all numbers
11. Count number of elements in an array
12. Find maximum number
13. Find minimum number
14. Reverse an array
15. Check if array contains a value
🟡 LEVEL 2: Intermediate (16–30)
16. Remove duplicate values
17. Count occurrences of each element
18. Find sum of even numbers
19. Get names of users above age 18
20. Convert array of objects to single object
21. Flatten a nested array (1 level)
22. Find average of numbers
23. Sort numbers without mutating original array
24. Group numbers into even and odd
25. Capitalize first letter of each word
26. Find longest string
27. Count vowels in a string
28. Find total salary from user objects
29. Check if array is palindrome
30. Convert array into key-value pairs
🔵 LEVEL 3: Advanced (31–45)
31. Compose multiple functions
32. Create a curried add function
33. Create a pipe function
34. Find intersection of two arrays
35. Find union of two arrays
36. Remove falsy values
37. Find most frequent element
38. Chunk array into fixed size
39. Find difference between two arrays
40. Sort objects by property
41. Deep flatten array
42. Convert array to tree structure
43. Memoize a pure function
44. Create immutable update helper
45. Create your own map function using reduce
🔴 LEVEL 4: Expert / Interview (46–50)
46. Implement filter() using reduce()
47. Implement reduce() from scratch
48. Create immutable Redux-style reducer
49. Lazy evaluation using closures
50. Build FP data pipeline (filter → map → reduce)
📌 Example (How to Solve – Sample)
Q: Sum of even numbers
const sumEven = arr =>
[Link](n => n % 2 === 0)
.reduce((a, b) => a + b, 0);
🎯 How I Recommend You Practice
🗓 Daily Plan (10 Days)
Day 1–3 → Level 1
Day 4–6 → Level 2
Day 7–8 → Level 3
Day 9–10 → Level 4
🧑🏫 Teacher Promise
If you want:
✔ Answers with explanations
✔ Hints only (no solutions)
✔ Interview-style discussion
✔ Daily practice schedule
✔ React-focused FP questions
Excellent 🔥
Now we step into Advanced Functional Programming — this is interview-level + real-world level, but I’ll still teach it
slowly, clearly, and practically.
🚀 Advanced Functional Programming (JavaScript)
We’ll cover core advanced FP concepts used in senior interviews, React, Redux, and libraries.
📚 Advanced FP Roadmap
1️⃣ Custom map, filter, reduce
2️⃣ pipe & compose (real utilities)
3️⃣ Closures & Lazy evaluation
4️⃣ Memoization
5️⃣ Referential transparency
6️⃣ Functors (map over context)
7️⃣ Monads (without fear 😄)
8️⃣ FP architecture patterns
Let’s go step by step.
1️⃣ Implement map() using reduce()
Concept
If you truly understand FP, you can build FP tools from FP tools.
const myMap = (arr, fn) =>
[Link]((acc, cur) => [...acc, fn(cur)], []);
✔ Immutable
✔ Declarative
✔ Interview favorite
2️⃣ Implement filter() using reduce()
const myFilter = (arr, predicate) =>
[Link](
(acc, cur) => predicate(cur) ? [...acc, cur] : acc,
[]
);
3️⃣ Implement reduce() from scratch
const myReduce = (arr, fn, initial) => {
let acc = initial;
for (let item of arr) {
acc = fn(acc, item);
return acc;
};
🧠 Interview tip:
Explain accumulator + iteration + return
4️⃣ pipe() vs compose()
Difference
Function Direction
compose right → left
pipe left → right
pipe() Implementation
const pipe = (...fns) =>
x => [Link]((v, f) => f(v), x);
Usage
const double = x => x * 2;
const add3 = x => x + 3;
const result = pipe(double, add3)(5);
[Link](result); // 13
5️⃣ Lazy Evaluation (Advanced Concept)
Idea
Compute only when needed
Example
const lazyAdd = a => b => () => a + b;
const add = lazyAdd(5)(3);
// nothing executed yet
[Link](add()); // 8
Used in:
Streams
Large data sets
Performance optimization
6️⃣ Memoization (Caching Results)
Idea
Save function result → reuse if same input appears again
Example
const memoize = fn => {
const cache = {};
return x => {
if (cache[x]) return cache[x];
cache[x] = fn(x);
return cache[x];
};
};
Usage
const slowSquare = n => {
for (let i = 0; i < 1e9; i++) {}
return n * n;
};
const fastSquare = memoize(slowSquare);
fastSquare(5);
fastSquare(5); // cached
7️⃣ Referential Transparency (VERY IMPORTANT)
Meaning
Function call can be replaced with its output.
add(2, 3) === 5
If true → referentially transparent
Pure functions guarantee this.
8️⃣ Functors (Map over a Context)
Simple Definition
A functor is anything that implements map.
Example: Array is a Functor
[1, 2, 3].map(x => x * 2);
Custom Functor
const Box = value => ({
map: fn => Box(fn(value)),
value
});
Box(5).map(x => x + 2).map(x => x * 3);
9️⃣ Monads (Without Fear 😄)
Simple Explanation
A monad:
✔ Is a functor
✔ Handles values inside a context safely
Example: Maybe Monad
const Maybe = value => ({
map: fn =>
value == null ? Maybe(null) : Maybe(fn(value)),
value
});
Usage
Maybe(5).map(x => x * 2).map(x => x + 1);
Maybe(null).map(x => x * 2); // safe
Used to:
✔ Avoid null errors
✔ Clean error handling
🔟 FP Architecture Pattern
Data Pipeline
Input
validate
transform
compute
output
Each step:
✔ Pure
✔ Independent
✔ Testable
🎯 Advanced Interview Questions (You Should Now Answer)
✔ What is referential transparency?
✔ Difference between functor & monad?
✔ Why memoization works only with pure functions?
✔ pipe vs compose?
🧑🏫 Teacher Challenge (Advanced)
Task 1:
Implement:
pipe(filter, map, reduce)
Task 2:
Create a safe divide using Maybe monad
🏆 You’re Now at Advanced Level
Prachi, at this point:
✔ You understand FP deeply
✔ You can crack interviews
✔ You can write clean React logic
Next, we can:
1️⃣ Solve Advanced FP interview problems
2️⃣ Learn FP + React patterns
3️⃣ Learn FP vs OOP deep coding
4️⃣ Build a mini FP utility library
Just tell me 🚀
Excellent choice, Prachi 🔥
FP + React patterns are exactly what interviewers and real projects care about.
I’ll teach this like a senior React mentor, but still simple and structured.
⚛️Functional Programming + React
🔑 Core Patterns You MUST Know
🧠 Big Idea (1-line)
React = UI as a pure function of state
UI = f(state, props)
1️⃣ Pure Components Pattern
❌ Impure Component
function Counter() {
let count = 0;
count++;
return <h1>{count}</h1>;
✅ Pure Component
function Counter({ count }) {
return <h1>{count}</h1>;
✔ Same props → same UI
✔ Predictable
✔ Testable
2️⃣ Immutability in State Updates
❌ Mutation (BUG PRONE)
[Link](newItem);
setState(state);
✅ FP-Correct
setItems(prev => [...prev, newItem]);
Update Object Immutably
setUser(prev => ({ ...prev, age: 22 }));
3️⃣ Functional Updates Pattern
Why?
State updates are async
❌ Risky
setCount(count + 1);
✅ Safe FP Style
setCount(prev => prev + 1);
✔ Uses pure function
✔ Avoids stale state bugs
4️⃣ Derived State (FP GOLD RULE)
❌ Anti-Pattern
const [total, setTotal] = useState(0);
✅ FP Pattern
const total = [Link]((sum, i) => sum + [Link], 0);
✔ No extra state
✔ No sync issues
✔ Declarative
5️⃣ useReducer = FP Reducer Pattern
When to use?
Complex state logic
Multiple related updates
Reducer Rules
✔ Pure function
✔ No mutation
✔ Same input → same output
Example
function reducer(state, action) {
switch ([Link]) {
case "ADD":
return [...state, [Link]];
case "REMOVE":
return [Link](i => [Link] !== [Link]);
default:
return state;
const [items, dispatch] = useReducer(reducer, []);
6️⃣ Data Transformation Outside JSX
❌ Bad Practice
{[Link](item => {
if ([Link] > 1000) {
return <p>{[Link]}</p>;
})}
✅ FP Clean Pattern
const expensiveItems = [Link](i => [Link] > 1000);
return [Link](i => <p key={[Link]}>{[Link]}</p>);
7️⃣ Custom Hooks = FP Abstraction
Pattern
Extract logic into pure reusable functions
Example
function useTotal(items) {
return [Link]((sum, i) => sum + [Link], 0);
✔ Declarative
✔ Reusable
✔ Testable
8️⃣ Memoization (useMemo, useCallback)
When?
Expensive calculations
Stable function references
Example
const total = useMemo(
() => [Link]((s, i) => s + [Link], 0),
[items]
);
Callback Memoization
const handleClick = useCallback(
() => setCount(c => c + 1),
[]
);
9️⃣ Composition over Logic
❌ One Big Component
function Dashboard() {
// fetch, filter, render, calculate
✅ FP Composition
const filterActive = users => [Link](u => [Link]);
const Dashboard = ({ users }) =>
filterActive(users).map(u => <User key={[Link]} user={u} />);
🔟 Controlled Components (FP Pattern)
<input value={name} onChange={e => setName([Link])} />
✔ UI reflects state
✔ State drives UI
🧠 React Interview GOLD Questions
✔ Why use functional updates?
✔ Why immutability is important in React?
✔ useState vs useReducer?
✔ Derived state vs stored state?
✔ How FP improves React performance?
🧑🏫 Mini React FP Challenge
Build a component that:
✔ Stores list of products
✔ Filters products > ₹1000
✔ Calculates total price
✔ Uses FP only (map, filter, reduce)
✔ Uses useReducer
🏆 You Are Now React-FP Ready
Prachi, this level is better than most freshers 👏
You now think like a React + FP developer.
Next options:
1️⃣ React FP interview coding questions
2️⃣ Build a mini React app using FP
3️⃣ FP performance optimization patterns
4️⃣ FP + Redux Toolkit patterns
Just tell me what’s next 🚀
Perfect 🔥
This is a deep, coding-level comparison of Functional Programming (FP) vs Object-Oriented Programming (OOP) —
exactly what interviewers love when you can explain + code + justify.
I’ll act like a senior teacher, and we’ll go problem → OOP solution → FP solution → analysis
⚔️FP vs OOP — Deep Coding Comparison (JavaScript)
🧠 Core Philosophy (1-line)
OOP FP
Data + behavior together Data flows through functions
State lives in objects State is passed & transformed
Mutation is common Immutability is preferred
1️⃣ SIMPLE PROBLEM
👉 Create a Counter
🔴 OOP Style
class Counter {
constructor() {
[Link] = 0;
increment() {
[Link]++;
decrement() {
[Link]--;
getValue() {
return [Link];
const c = new Counter();
[Link]();
[Link]();
[Link]([Link]());
❌ Issues
Hidden mutable state
Hard to debug in large apps
🟢 FP Style
const increment = count => count + 1;
const decrement = count => count - 1;
let count = 0;
count = increment(count);
count = increment(count);
[Link](count);
✅ Benefits
No hidden state
Easy testing
Predictable
2️⃣ SHOPPING CART PROBLEM
👉 Add & Remove Items
🔴 OOP Approach
class Cart {
constructor() {
[Link] = [];
add(item) {
[Link](item);
remove(id) {
[Link] = [Link](i => [Link] !== id);
total() {
return [Link]((s, i) => s + [Link], 0);
🟢 FP Approach
const addItem = (cart, item) => [...cart, item];
const removeItem = (cart, id) =>
[Link](i => [Link] !== id);
const total = cart =>
[Link]((s, i) => s + [Link], 0);
🧠 Analysis
OOP FP
Methods mutate object Functions return new data
Hard to test Easy unit tests
Tightly coupled Loosely coupled
3️⃣ USER UPDATE PROBLEM
👉 Update User Age
🔴 OOP
class User {
constructor(name, age) {
[Link] = name;
[Link] = age;
birthday() {
[Link]++;
const u = new User("A", 20);
[Link]();
🟢 FP
const birthday = user => ({
...user,
age: [Link] + 1
});
const user = { name: "A", age: 20 };
const updatedUser = birthday(user);
4️⃣ COMPLEX LOGIC
👉 Order Processing Pipeline
🔴 OOP
class Order {
constructor(items) {
[Link] = items;
applyDiscount() {
[Link](i => [Link] *= 0.9);
getTotal() {
return [Link]((s, i) => s + [Link], 0);
❌ Side effects
❌ Hard to trace bugs
🟢 FP (PIPELINE)
const discount = items =>
[Link](i => ({ ...i, price: [Link] * 0.9 }));
const total = items =>
[Link]((s, i) => s + [Link], 0)
const processOrder = items => total(discount(items));
✔ Declarative
✔ Clear flow
✔ Testable steps
5️⃣ ERROR HANDLING
👉 Safe Division
🔴 OOP (Exceptions)
class Calculator {
divide(a, b) {
if (b === 0) throw Error("Invalid");
return a / b;
🟢 FP (Maybe Monad)
const Maybe = v => ({
map: fn => v == null ? Maybe(null) : Maybe(fn(v)),
value: v
});
const safeDivide = (a, b) =>
b === 0 ? Maybe(null) : Maybe(a / b);
6️⃣ TESTING COMPARISON
FP Test (Easy)
expect(increment(2)).toBe(3);
OOP Test (Harder)
const c = new Counter();
[Link]();
expect([Link]()).toBe(1);
🧠 WHEN TO USE WHAT?
Use FP when:
✔ Data transformation heavy
✔ React / Redux
✔ Predictability matters
Use OOP when:
✔ Complex entities
✔ Real-world modeling
✔ Large domain logic
🏆 INTERVIEW POWER ANSWER
“Modern JavaScript apps use FP for logic and OOP for structure.”
🧑🏫 FINAL CHALLENGE
Convert this OOP code to FP:
class Bank {
constructor(balance) {
[Link] = balance;
deposit(amount) {
[Link] += amount;
withdraw(amount) {
[Link] -= amount;
Perfect 🔥
I’ll cover ALL 4, in a teacher + interviewer style, with clear structure, deep answers, and real coding.
Save this — it’s gold for interviews.
1️⃣ FP vs OOP — INTERVIEW Q&A (DEEP + SMART ANSWERS)
Q1. What is the main difference between FP and OOP?
Answer (Strong):
OOP organizes code around objects and mutable state, while FP organizes code around pure functions and
immutable data flows.
Q2. Why is FP preferred in React?
Answer:
React UI = pure function of state
Immutability enables fast re-rendering
Predictable updates using reducers
Q3. What problems does FP solve better than OOP?
Answer:
State-related bugs
Side effects
Debugging complexity
Concurrency issues
Q4. Can FP and OOP be used together?
Answer (BEST):
Yes. Modern applications use FP for logic and OOP for structure and domain modeling.
Q5. Why are pure functions easy to test?
Answer:
No hidden dependencies
Same input → same output
No mocks needed
Q6. What is immutability and why is it important?
Answer:
Immutability means not changing existing data.
It helps with:
Debugging
React re-renders
Undo/redo
Predictability
Q7. FP or OOP — which is faster?
Answer:
Neither by default. Performance depends on implementation, not paradigm.
2️⃣ CONVERT OOP PROJECT → FP (REAL EXAMPLE)
🎯 OOP PROJECT: BANK SYSTEM
🔴 OOP Version
class Bank {
constructor(balance = 0) {
[Link] = balance;
deposit(amount) {
[Link] += amount;
withdraw(amount) {
[Link] -= amount;
getBalance() {
return [Link];
❌ Mutable
❌ Hidden state
🟢 FP VERSION
const deposit = (balance, amount) => balance + amount;
const withdraw = (balance, amount) => balance - amount;
let balance = 0;
balance = deposit(balance, 500);
balance = withdraw(balance, 200);
✔ No mutation
✔ Easy testing
✔ Stateless
🧠 FP PIPELINE VERSION
const process = balance =>
balance
|> b => deposit(b, 500)
|> b => withdraw(b, 200);
3️⃣ HYBRID FP + OOP ARCHITECTURE (REAL-WORLD)
🏗 Best Industry Pattern
OOP → structure, entities
FP → business logic
🧩 Example: E-Commerce App
OOP (Structure)
class Product {
constructor(id, price) {
[Link] = id;
[Link] = price;
FP (Logic)
const applyDiscount = (price, rate) => price * (1 - rate);
const calculateTotal = products =>
[Link]((s, p) => s + [Link], 0);
🔥 React Example (Hybrid)
function Cart({ products }) {
const total = calculateTotal(products);
return <h2>Total: {total}</h2>;
✔ OOP: component structure
✔ FP: data transformation
4️⃣ MOCK INTERVIEW (React + FP) 🎤
Interviewer:
Why use useReducer instead of useState?
You:
When state logic becomes complex, useReducer helps by using a pure reducer function, making updates predictable
and easier to test.
Interviewer:
How does FP improve React performance?
You:
Through immutability and memoization, React can quickly detect changes and avoid unnecessary re-renders.
Interviewer:
Explain derived state.
You:
Derived state is computed from existing state using pure functions instead of storing it separately.
Interviewer:
Show FP-style state update.
setItems(prev => [...prev, newItem]);
Interviewer:
What FP concepts do you use daily?
You (Perfect Answer):
Pure functions, immutability, map/filter/reduce, function composition, and reducers.
🏆 FINAL INTERVIEW SUMMARY (Say This)
“I follow a hybrid approach — FP for predictable logic and OOP for clean structure, especially in React applications.”
Fantastic choice 🚀
We’ll build a real mini Functional Programming utility library step by step, exactly how senior devs do it.
I’ll teach you design + code + usage, and by the end you’ll have a GitHub-ready FP library you can proudly show in
interviews.
🧩 Mini FP Utility Library (JavaScript)
Library name: fp-lite
🎯 Design Goals
✔ Pure functions only
✔ No mutation
✔ Small & reusable
✔ Chainable (pipe/compose)
✔ Interview-friendly
📁 Project Structure
fp-lite/
├── [Link]
├── [Link]
├── [Link]
├── [Link]
└── [Link]
(We’ll write everything here 👇)
1️⃣ Core Utilities ([Link])
🔗 pipe
export const pipe = (...fns) =>
input => [Link]((val, fn) => fn(val), input);
🔁 compose
export const compose = (...fns) =>
input => [Link]((val, fn) => fn(val), input);
🍛 curry
export const curry = fn =>
curried(...args) =>
[Link] >= [Link]
? fn(...args)
: (...next) => curried(...args, ...next);
🧠 memoize
export const memoize = fn => {
const cache = {};
return (...args) => {
const key = [Link](args);
return cache[key] ??= fn(...args);
};
};
2️⃣ Array Utilities ([Link])
🔄 map
export const map = fn => arr =>
[Link]((acc, x) => [...acc, fn(x)], []);
🔍 filter
export const filter = predicate => arr =>
[Link](
(acc, x) => predicate(x) ? [...acc, x] : acc,
[]
);
🧮 reduce
export const reduce = (fn, init) => arr =>
[Link](fn, init);
🔢 unique
export const unique = arr =>
[...new Set(arr)];
✂️chunk
export const chunk = size => arr =>
[Link]((acc, x, i) => {
const idx = [Link](i / size);
acc[idx] = acc[idx] || [];
acc[idx].push(x);
return acc;
}, []);
3️⃣ Object Utilities ([Link])
🧩 pick
export const pick = keys => obj =>
[Link]((acc, k) => {
if (k in obj) acc[k] = obj[k];
return acc;
}, {});
🔄 omit
export const omit = keys => obj =>
[Link](obj)
.filter(k => )
.reduce((acc, k) => ({ ...acc, [k]: obj[k] }), {});
🧼 update
export const update = (key, fn) => obj =>
({ ...obj, [key]: fn(obj[key]) });
4️⃣ Entry Point ([Link])
export * from "./[Link]";
export * from "./[Link]";
export * from "./[Link]";
5️⃣ USING YOUR FP LIBRARY (🔥 Real Example)
import { pipe, map, filter, reduce } from "./fp-lite";
const process = pipe(
filter(n => n > 0),
map(n => n * 2),
reduce((a, b) => a + b, 0)
);
process([1, -2, 3, 4]); // 1
⚛️React Usage Example
const total = pipe(
filter(p => [Link] > 1000),
map(p => [Link]),
reduce((s, p) => s + p, 0)
)(products);
✔ Clean
✔ Declarative
✔ FP-pure
🧠 Interview Explanation (Say This)
“I built a small FP utility library implementing pipe, curry, memoize, and immutable data helpers to enforce
predictable state updates in React.”
🧪 EXTENSIONS (Next Level)
You can add:
✔ flatMap
✔ groupBy
✔ debounce (functional style)
✔ Maybe monad
✔ Either monad
🧑🏫 FINAL CHALLENGE
1️⃣ Add groupBy(fn)
2️⃣ Add flatMap(fn)
3️⃣ Write unit tests (Jest style)
If you want, next I can:
📦 Convert this into an npm package
🧪 Write tests
🧾 Create a README
🎤 Do mock interview using this library
Just tell me 👑