MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Memoization & Pure Functions0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
HomeTutorialsJavaScript for AdvancedMemoization & Pure Functions
Execution Context & Call Stack Deep Dive

Memoization & Pure Functions

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Performance optimization in data-heavy and graphics-intensive web applications requires minimizing redundant calculations. By combining Pure Functions with Memoization, algorithms can trade memory for processing speed—caching previously computed results and retrieving them in $O(1)$ constant time.


1. The Foundation: Pure Functions

A function is considered pure if and only if it satisfies two conditions:

  1. 1
    Deterministic: Given the same arguments, it always returns the exact same result.
  2. 2
    No Side Effects: It does not mutate external state, perform I/O, modify global variables, or manipulate the DOM.
1// PURE FUNCTION: Deterministic, zero side effects
2function calculateTax(amount, taxRate) {
3 return amount * (1 + taxRate);
4}
5 
6// IMPURE FUNCTION: Depends on external mutable state and time
7let exchangeRate = 1.25;
8function convertCurrency(amount) {
9 return amount * exchangeRate; // Impure: Result changes if exchangeRate changes!
10}
Golden Rule: Only pure functions can be safely memoized! Memoizing an impure function will return stale cached values even when underlying conditions change.

2. What is Memoization?

Memoization is an optimization technique where a function caches its return values corresponding to specific input arguments. When invoked with arguments seen previously, it returns the cached result instead of re-evaluating the computation.

1Function Invocation: fib(40)
2 ├── 1st Call ──► Compute via CPU (takes 850ms) ──► Store in Cache ──► Return 102334155
3 └── 2nd Call ──► Found in Cache! ──► Immediate Return (takes 0.02ms)

3. Implementing a Generic Memoizer

1function memoize(fn) {
2 const cache = new Map();
3 
4 return function (...args) {
5 // Generate cache key by serializing arguments
6 const key = JSON.stringify(args);
7 
8 if (cache.has(key)) {
9 console.log(`[Cache Hit] for arguments: ${key}`);
10 return cache.get(key);
11 }
12 
13 console.log(`[Cache Miss] Computing result for: ${key}`);
14 const result = fn.apply(this, args);
15 cache.set(key, result);
16 return result;
17 };
18}

Benchmarking Expensive Recursive Fibonacci

1// Unmemoized: O(2^n) exponential disaster
2function fibonacci(n) {
3 if (n <= 1) return n;
4 return fibonacci(n - 1) + fibonacci(n - 2);
5}
6 
7// Memoized version
8const fastFib = memoize(function fib(n) {
9 if (n <= 1) return n;
10 return fastFib(n - 1) + fastFib(n - 2);
11});
12 
13console.time('FastFib');
14console.log(fastFib(40)); // 102334155 (Runs in ~1 millisecond!)
15console.timeEnd('FastFib');

4. Memory Management: LRU (Least Recently Used) Caching

An unbounded cache Map can cause memory leaks if called with millions of unique arguments. In production, use an LRU Cache that discards the least recently used keys when exceeding a capacity threshold:

1class LRUCache {
2 constructor(maxSize = 100) {
3 this.maxSize = maxSize;
4 this.cache = new Map();
5 }
6 
7 get(key) {
8 if (!this.cache.has(key)) return undefined;
9 // Re-insert to mark as most recently used
10 const val = this.cache.get(key);
11 this.cache.delete(key);
12 this.cache.set(key, val);
13 return val;
14 }
15 
16 set(key, value) {
17 if (this.cache.has(key)) {
18 this.cache.delete(key);
19 } else if (this.cache.size >= this.maxSize) {
20 // Evict oldest entry (first key in map)
21 const oldestKey = this.cache.keys().next().value;
22 this.cache.delete(oldestKey);
23 }
24 this.cache.set(key, value);
25 }
26}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What makes a function "pure" in functional programming?
Question 2
Why is it dangerous to memoize an impure function (e.g. one reading current time or external database state)?
Question 3
What computational complexity does retrieving a memoized result from a hash map achieve?
Question 4
What common bug can occur if a generic memoize cache stores unlimited results without an eviction policy?
Question 5
What cache eviction strategy discards the least recently accessed items when reaching maximum capacity?
Next Lesson

Execution Context & Call Stack Deep Dive

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Function Composition & PipeliningExecution Context & Call Stack Deep Dive

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext