🚀 Frontend DSA 2 -⚡Supercharge Your JavaScript Functions with Caching (Memoization)
Are your JavaScript functions doing redundant work with the same inputs over and over again? 🤔 That’s where caching (also called memoization) steps in to save time and resources!
In this tutorial, you’ll learn how to create a JavaScript caching utility that can wrap any function and return cached results if the inputs haven't changed. 🔄
Let’s build it step by step. 👇
🧩 What is Function Caching (Memoization)?
Memoization is a powerful performance optimization technique that stores the result of function calls and returns the cached result when the same inputs occur again.
🚀 Use Case: Caching a sum(a, b)
Function
Let’s say we have a simple function:
function sum(a, b) {
return a + b;
}
It’s fast now, but imagine it being a heavy calculation (like factorial, Fibonacci, or an API call). We don't want to repeat it unnecessarily. So we cache the results! 🗃️
🔧 Creating the Caching Utility
Let’s write a function cachedSumFun
that:
- Takes a function as an argument 🧠
- Stores previous results in a
Map
🗺️ - Returns the cached result if called again with the same parameters ✅
- Calls the original function if inputs change 🔄
Here’s the code with comments:
// 👨🏫 A simple sum function
function sum(a, b) {
return a + b;
}
// 🧠 Caching utility to wrap any function
function cachedSumFun(func) {
let cache = new Map(); // Using Map to store cached results
return function(a, b) {
let uniqueKey = `pre${a}:${b}`; // Create a unique key for arguments
if (cache.has(uniqueKey)) {
console.log("🗃️ Returning from cache for:", a, b);
return cache.get(uniqueKey); // Return cached result
} else {
console.log("⚙️ Calculating result for:", a, b);
let result = func(a, b); // Call original function
cache.set(uniqueKey, result); // Store in cache
return result;
}
};
}
// ✅ Create a cached version of sum
const cacheSum = cachedSumFun(sum);
Problem Statement
🧪 Sample Inputs and Outputs
Let’s try it out with different inputs:
console.log(cacheSum(1, 2)); // ⚙️ Calculated → 3
console.log(cacheSum(1, 2)); // 🗃️ Cached → 3
console.log(cacheSum(2, 3)); // ⚙️ Calculated → 5
console.log(cacheSum(2, 3)); // 🗃️ Cached → 5
✅ Output:
⚙️ Calculating result for: 1 2
3
🗃️ Returning from cache for: 1 2
3
⚙️ Calculating result for: 2 3
5
🗃️ Returning from cache for: 2 3
5
💡 JavaScript Notes for Beginners
Map
is preferred over plain objects for caching because it maintains the insertion order and allows any type of key.cache.set(key, value)
saves the result.cache.has(key)
checks if the result is already stored.return function(a, b)
allows us to return a new function that wraps the original one.
🌍 Real-Life Use Cases
🔁 Caching is useful when:
- You're calling a slow computation repeatedly
- You want to avoid duplicate API calls
- You need to optimize recursive functions (like Fibonacci)
- You’re building search filters or dropdowns with repeated values
🏁 Final Thoughts
Caching makes your code faster, smarter, and scalable! 🔥
With just a few lines, you’ve learned how to wrap any function and prevent redundant work.
✨ Challenge for You!
Try wrapping more functions like:
multiply(a, b)
fibonacci(n)
factorial(n)
and cache their results using the same technique! 🧠
Hey there from LearnYard! 👋
Glad to see you exploring the free content from our course! We’ve shared 10 valuable articles at no cost to help you get a real feel of what’s inside.
If you’ve found these helpful, we’d love to know! 💬
Share your thoughts or key takeaways on LinkedIn, Twitter, or Instagram — and don’t forget to tag Gourav Hammad & Mohammad Fraz. We’ll personally respond to your post!
Thanks for being part of the LearnYard journey. Keep learning, keep growing! 🚀
Loved the free content? Want access to the full course — for free? 💸
Share the course with your friends using your affiliate link (you’ll find it on your profile or home page), and earn 20% commission on each sale.
Just 4–5 sales and you’ll recover the full course price of your course 🔁
So why wait? Start sharing, start earning, and unlock the rest of the course effortlessly! 🛠️📈
📚 Keywords for SEO
- JavaScript Function Caching Explained
- Memoization in JavaScript
- How to Optimize JavaScript Performance with Memoization
- JavaScript Cache Wrapper Function
- Higher-Order Function Example in JavaScript
- Return Cached Result in JS Functions
- JavaScript Memoization Utility
- Improving Function Performance in JavaScript
- Reusable Memoize Function in JS
- JavaScript Functional Programming Tips
📢 Hashtags for Visibility
#JavaScriptPerformance #Memoization #FunctionCaching #WebOptimization
#HigherOrderFunctions #CodeSmart #JSPerformanceTips #ReturnCachedResult
#JSForBeginners #LearnJavaScript #FrontendDevelopment #CodeNewbie
#JavaScriptTips #FunctionalProgramming #MemoizeJS #CodingBestPractices
#JSDeepDive #FrontendMasters #TechLearning #JavaScriptEssentials