JavaScript Functions & Concepts: Debounce, Throttle, Memoization & More

🚀 Day 24 – Functions & Advanced Concepts in JavaScript Today’s focus is not just theory — it’s how these concepts are used in REAL applications 👇 🔹 1. Debounce 👉 Executes function only after user stops triggering it for a delay. function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } Real-time scenario: In an e-commerce website, when a user searches for a product, we don’t call API on every keystroke. Instead, we wait until the user stops typing → then trigger API. 👉 Prevents 20+ unnecessary API calls! 🔹 2. Throttle 👉 Ensures function runs only once in a given interval. function throttle(fn, limit) { let flag = true; return function (...args) { if (!flag) return; flag = false; fn.apply(this, args); setTimeout(() => { flag = true; }, limit); }; } Real-time scenario: While scrolling Instagram/LinkedIn feed, scroll events fire continuously. Throttle ensures smooth performance by limiting executions. 👉 Prevents UI lag & improves performance 🔹 3. Currying 👉 Converts multiple arguments into nested functions. function curry(a) { return function (b) { return function (c) { return a + b + c; }; }; } console.log(curry(2)(3)(4)); // 9 Real-time scenario: In large apps, we create reusable utility functions. Example: Tax calculator → instead of passing all values every time, we reuse partial functions. 👉 Helps in clean & reusable code 🔹 4. Memoization 👉 Caches results to avoid recalculating. function memoize(fn) { const cache = {}; return function (n) { if (cache[n]) return cache[n]; const result = fn(n); cache[n] = result; return result; }; } Real-time scenario: In dashboards (finance/analytics apps), heavy calculations run repeatedly. Memoization stores results → avoids recomputation. 🔹 5. Closures ⭐ 👉 A function remembers variables from its outer scope even after execution. function outer() { let count = 0; return function inner() { count++; return count; }; } const counter = outer(); console.log(counter()); // 1 console.log(counter()); // 2 Real-time scenario: ✔ Data hiding ✔ Maintaining state (like counters, caches) Used in: ✔ Counters (cart items count) ✔ Private variables (data hiding) ✔ setTimeout inside loops 👉 Helps maintain state without global variables 🔹 6. Pure Functions 👉 Function that always returns same output for same input and has no side effects. function add(a, b) { return a + b; } Real-time scenario: In state management (Angular/React), pure functions ensure predictable updates. Why important? ✔ Predictable ✔ Easy to test ✔ Used in frameworks like Angular & React 👉 Easier debugging & testing #JavaScript #FrontendDeveloper #Angular #InterviewPrep #Coding #WebDevelopment

To view or add a comment, sign in

Explore content categories