Monday, 4 Aug 2025
  • My Interests
  • My Saves
  • Try Intents
Subscribe
Focus - Code Reveals
  • Home
  • HTML

    What are the async and defer attributes in the “script” tag?

    By Chief Editor

    What are the different types of HTML tags?

    By Chief Editor

    What is the difference between “HTML” and “HTML5”?

    By Chief Editor

    What is Doctype HTML in HTML?

    By Chief Editor

    What is Block level Element and Inline Level Element?

    By Chief Editor
    What is Symentic HTML

    What is Symentic HTML?

    By Chief Editor
  • JavaScript

    What is a Closure in JavaScript?

    By Chief Editor

    What is memoization in JavaScript?

    By Chief Editor
    What are the Lexical Scope in JavaScript

    What are the Lexical Scope in JavaScript?

    By Chief Editor

    What is Arrow and Normal Function in JavaScript?

    By Chief Editor

    Explain Call, Apply and Bind in JavaScript.

    By Chief Editor

    Explain Deep Copy and Shallow Copy in JavaScript.

    By Chief Editor
  • Frontend Interview

    Explain Deep Copy and Shallow Copy in JavaScript.

    By Chief Editor

    What is Position in CSS?

    By Chief Editor

    How to Reverse a String in JavaScript: Two Essential Methods

    By Chief Editor

    What is Symentic HTML?

    By Chief Editor

    Difference Between position: relative and position: absolute in CSS

    By Chief Editor

    What are the Lexical Scope in JavaScript?

    By Chief Editor
  • Backend Interview

    What is Flex Box in CSS?

    By Chief Editor

    Explain Call, Apply and Bind in JavaScript.

    By Chief Editor

    What is Block level Element and Inline Level Element?

    By Chief Editor

    What is memoization in JavaScript?

    By Chief Editor

    Explain the useState and useEffect hooks in React

    By Chief Editor

    What are Benefits in React?

    By Chief Editor
  • Nodejs
  • JavaScript Interview
  • React Interview
  • Frontend Interview
  • Backend Interview
  • Contact Us
  • Advertise with Us
  • Complaint
  • Cookies Policy
  • Privacy Policy
  • Donate
  • 🔥
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • React Interview
  • HTML
  • Frontend Interview
  • CSS
  • Redux
  • Javascript
  • System Design
Font ResizerAa
Focus - Code RevealsFocus - Code Reveals
  • My Saves
  • My Interests
  • My Feed
  • History
  • Technology
Search
  • Homepage
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • HTML
  • CSS
  • Backend Interview
Have an existing account? Sign In
Follow US
© 2022 Code Reveals Inc. All Rights Reserved.
Home Blog What is memoization in JavaScript?
JavaScriptJavaScript Interview

What is memoization in JavaScript?

Chief Editor
Last updated: February 16, 2025 1:21 pm
Chief Editor
Share
SHARE

Memoization is an optimization technique used in JavaScript (and other programming languages) to speed up the execution of functions by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

Contents
How Does Memoization Work?Example: Without MemoizationExample: With MemoizationKey Points about Memoization:When to Use Memoization:Simple Memoization Utility Function

How Does Memoization Work?

  • When a function is called, its result is stored in a cache (object).
  • If the same input is provided again, the cached result is returned instead of recalculating the result.
  • This improves performance, especially for heavy calculations or recursive functions (e.g., Fibonacci, Factorials).

Example: Without Memoization

javascriptCopyEditfunction factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

console.log(factorial(5)); // 120

This works but recalculates the result every time, which is inefficient for large inputs or repeated calls.


Example: With Memoization

javascriptCopyEditfunction memoizedFactorial() {
  const cache = {};

  return function factorial(n) {
    if (n in cache) {
      console.log('Fetching from cache:', n);
      return cache[n];
    } else {
      console.log('Calculating result:', n);
      if (n <= 1) return 1;
      const result = n * factorial(n - 1);
      cache[n] = result;
      return result;
    }
  };
}

const factorial = memoizedFactorial();
console.log(factorial(5)); // Calculating result...
console.log(factorial(5)); // Fetching from cache

Key Points about Memoization:

FeatureDescription
PurposeAvoid redundant calculations by caching results.
Performance BenefitUseful for expensive functions (e.g., recursion).
Data Structure UsedUsually an object ({}) is used as a cache.
Input as KeyInputs act as keys in the cache to retrieve results.

When to Use Memoization:

  • Expensive Computations – Functions that take a lot of time to compute.
  • Recursive Problems – Problems like Fibonacci sequence, Factorials, and Dynamic Programming.
  • Repeated Calls with Same Input – When the same input is expected to be used multiple times.

Simple Memoization Utility Function

javascriptCopyEditfunction memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache[key]) {
      console.log('Fetching from cache:', args);
      return cache[key];
    } else {
      console.log('Calculating result:', args);
      const result = fn(...args);
      cache[key] = result;
      return result;
    }
  };
}

// Usage example:
const add = (a, b) => a + b;
const memoizedAdd = memoize(add);

console.log(memoizedAdd(1, 2)); // Calculating result
console.log(memoizedAdd(1, 2)); // Fetching from cache

Memoization is a powerful technique for improving the efficiency of functions, especially when dealing with large datasets or complex calculations.

Share This Article
Email Copy Link Print
Previous Article What is Arrow and Normal Function in JavaScript?
Next Article What are the Rest and Spread operators in JavaScript?
Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Your Trusted Source for Accurate and Timely Updates!

Our commitment to accuracy, impartiality, and delivering breaking news as it happens has earned us the trust of a vast audience. Stay ahead with real-time updates on the latest events, trends.
FacebookLike
XFollow
InstagramFollow
YoutubeSubscribe
LinkedInFollow
QuoraFollow
- Advertisement -
Ad imageAd image

Popular Posts

What is middleware, and what is React Thunk?

Middleware in the context of Redux (and other systems, like web servers) refers to a…

By Chief Editor

What is Block level Element and Inline Level Element?

Block-level Elements Block-level elements occupy the entire width of their parent container (by default) and…

By Chief Editor

Explain the uesReducer and useContext hooks in React

useReducer and useContext Hooks in React 1. useReducer Hook Purpose: The useReducer hook is an…

By Chief Editor

You Might Also Like

JavaScriptJavaScript Interview

What is one-way data binding in React?

By Chief Editor
JavaScriptJavaScript Interview

What is Callback Hell in JavaScript?

By Chief Editor
JavaScriptJavaScript Interview

Difference between document.createElement and document.createElementFragement in JavaScript?

By Chief Editor
JavaScriptJavaScript Interview

What is the this Keyword in JavaScript?

By Chief Editor

Focus by CodeReveals is your dedicated platform for mastering tech interviews and advancing your development skills. Whether you’re aiming to become a Frontend Developer, Backend Developer, or simply preparing for your next big interview, we’re here to guide you every step of the way.

Our mission is to help aspiring developers gain real-world knowledge, build confidence, and succeed in technical interviews. We offer structured content, curated interview questions, coding challenges, and practical guidance — all designed by experienced professionals who understand what top tech companies are looking for.

At Improve, we don’t just teach — we prepare you to think like a developer, solve like an engineer, and present like a pro.

Join us and start improving today — because your dream tech job is within reach

Most Famous
  • HTML
  • CSS
  • JavaScript
  • NodeJS
Top Categories
  • JavaScript Interview
  • React Interview
  • Frontend Interview
  • Backend Interview
Usefull Links
  • Contact Us
  • Advertise with Us
  • Complaint
  • Cookies Policy
  • Privacy Policy
  • Donate

©2025  Code Reveals Inc. All Rights Reserved.

Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?