Thursday, 3 Jul 2025
  • My Feed
  • My Interests
  • My Saves
  • History
  • Blog
Subscribe
Code Reveals
  • Home
  • HTML
    What is Symentic HTML

    What is Symentic HTML?

    By Chief Editor

    What is Block level Element and Inline Level Element?

    By Chief Editor

    Difference between HTML Tag and HTML Element in HTML?

    By Chief Editor

    What is Doctype HTML in HTML?

    By Chief Editor

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

    By Chief Editor

    What is a Meta Tag in HTML?

    By Chief Editor
  • JavaScript

    Is JavaScript a synchronous or asynchronous language?

    By Chief Editor

    What is Arrow and Normal Function in JavaScript?

    By Chief Editor

    What is a Promise in JavaScript, and what are its parameters?

    By Chief Editor

    What are the Rest and Spread operators in JavaScript?

    By Chief Editor

    What is a Closure in JavaScript?

    By Chief Editor

    What is one-way data binding in React?

    By Chief Editor
  • Frontend Interview

    What is Block level Element and Inline Level Element?

    By Chief Editor

    What is Symentic HTML?

    By Chief Editor

    Difference Between position: relative and position: absolute in CSS

    By Chief Editor

    How to Reverse a String in JavaScript: Two Essential Methods

    By Chief Editor

    What are the Lexical Scope in JavaScript?

    By Chief Editor

    Is JavaScript a synchronous or asynchronous language?

    By Chief Editor
  • Backend Interview

    What is Scope in JavaScript?

    By Chief Editor

    What are controlled and uncontrolled components in React?

    By Chief Editor

    What is React Fiber and its importance in react?

    By Chief Editor

    How Can You Share Data Between Components in React?

    By Chief Editor

    What is Symentic HTML?

    By Chief Editor

    What are the drawbacks of React?

    By Chief Editor
  • Other
    • Contact Us
  • Frontend Interview
  • Backend Interview
  • React Interview
  • JavaScript Interview
  • Contacts Us
  • Advertise with Us
  • Complaint
  • Privacy Policy
  • Cookie Policy
  • Submit a Tip
  • 🔥
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • React Interview
  • HTML
  • Frontend Interview
  • CSS
  • Redux
  • Javascript
  • System Design
Font ResizerAa
Code RevealsCode Reveals
  • My Saves
  • My Interests
  • My Feed
  • History
  • Technology
Search
  • Homepage
  • Pages
    • Home
    • Blog Index
    • Contact Us
    • Search Page
    • 404 Page
  • Features
    • Post Headers
    • Layout
  • Personalized
    • My Feed
    • My Saves
    • My Interests
    • History
  • About
  • Categories
    • Technology
  • Categories
Have an existing account? Sign In
Follow US
© 2022 Code Reveals Inc. All Rights Reserved.

Home 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 Life Cycle method in React?

In React, lifecycle methods are special methods that are automatically called at different stages of…

By Chief Editor

What is Callback Hell in JavaScript?

Callback Hell in JavaScript refers to a situation where you have multiple nested callbacks, making…

By Chief Editor

How Does React Work?

React is a JavaScript library used for building user interfaces, particularly for single-page applications (SPAs).It…

By Chief Editor

You Might Also Like

JavaScriptFrontend Interview

Explain Deep Copy and Shallow Copy in JavaScript.

By Chief Editor
Frontend InterviewJavaScript

How to Reverse a String in JavaScript: Two Essential Methods

By Chief Editor
JavaScript

What is a Closure in JavaScript?

By Chief Editor
JavaScriptJavaScript Interview

What is the this Keyword in JavaScript?

By Chief Editor

Code Reveals is a cutting-edge software development company dedicated to delivering high-quality, scalable, and innovative solutions for businesses of all sizes. Our team of expert developers, designers, and engineers specializes in creating custom software, web applications, mobile apps, and enterprise solutions that are tailored to meet the unique needs of our clients.

Most Famous
  • HTML
  • CSS
  • JavaScript
  • Node
Top Categories
  • Frontend Interview
  • Backend Interview
  • React Interview
  • JavaScript Interview
Usefull Links
  • Contacts Us
  • Advertise with Us
  • Complaint
  • Privacy Policy
  • Cookie Policy
  • Submit a Tip

©2025  Code Reveals Inc. All Rights Reserved.

Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?