Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to transform String into a function in JavaScript ?
Next article icon

How to write a simple code of Memoization function in JavaScript ?

Last Updated : 17 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Memoization is a programming technique that we used to speed up functions and it can be used to do whenever we have an expensive function ( takes a long time to execute). It relies on the idea of cache {}. A cache is just a plain object. It reduces redundant function expression calls.

Let’s understand how to write a  simpler code of the Memoization function in JS.

Example 1: In this example, we will see the inefficient way of writing a function that takes more time to compute.  

Javascript




const square = (n) => {
    let result = 0;
 
    // Slow function
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= n; j++) {
            result += 1;
        }
    }
    return result;
}
 
console.log(square(10000006));
console.log(square(40));
console.log(square(5));
 
 

Output:

For this reason, to compute operation in less time for large, we use memoization.

There are two ways to do memoization:

  • Function memoization
  • Cache memoization

Slow function which takes a large time to compute using cache memoization.

Example 2: This example is used to find the Square of number

Javascript




const preValues = []
function square(n) {
    if (preValues[n] != null) {
        return preValues[n]
    }
    let result = 0;
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= n; j++) {
            result += 1;
        }
    }
 
    // Storing precomputing value
    preValues[n] = result;
    return result;
}
 
console.log(square(50000));
console.log(square(5000));
console.log(square(500));
 
 
Output
2500000000 25000000 250000

Uses in Dynamic programming using cache memoization.

Example 3: This example is used to print Fibonacci sequence

Javascript




fib = (n, preValues = []) => {
    if (preValues[n] != null)
        return preValues[n];
    let result;
 
    if (n <= 2)
        result = 1;
    else
        result = fib(n - 1, preValues) + fib(n - 2, preValues);
 
    preValues[n] = result;
    return result;
}
 
console.log(fib(100));
 
 
Output
354224848179262000000

Using memoizer i.e. it takes a function and then it has to return a function.

Example 4: This example shows memoization in JavaScript

Javascript




// Memoizer
const memoize = () => {
 
    // Create cache for results
    // Empty objects
    const results = {};
 
    // Return function which takes
    // any number of arguments
    return (...args) => {
        // Create key for cache
        const argsKey = JSON.stringify(args);
 
        // Only execute func if no cached val
        // If results object does not have
        // anything to argsKey position
        if (!results[argsKey]) {
            results[argsKey] = func(...args)
        }
        return results[argsKey];
    };
};
 
// Wrapping memoization function
const multiply = memoize((num1, num2) => {
    let total = 0;
    for (let i = 0; i < num1; i++) {
        for (let j = 0; j < num1; j++) {
 
            // Calculating square
            total += 1 *;
        }
    }
 
    // Multiplying square with num2
    return total * num2;
});
 
console.log(multiply(500, 5000));
 
 

Output:

1250000000


Next Article
How to transform String into a function in JavaScript ?
author
surbhikumaridav
Improve
Article Tags :
  • Geeks Premier League
  • JavaScript
  • Web Technologies
  • ES6
  • Geeks-Premier-League-2022
  • JavaScript-Questions

Similar Reads

  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 min read
  • How to Store an Object sent by a Function in JavaScript ?
    When a function in JavaScript returns an object, there are several ways to store this returned object for later use. These objects can be stored in variables, array elements, or properties of other objects. Essentially, any data structure capable of holding values can store the returned object. Tabl
    2 min read
  • How to transform String into a function in JavaScript ?
    In this article, we will see how to transform a String into a function in JavaScript. There are two ways to transform a String into a function in JavaScript. The first and easy one is eval() but it is not a secure method as it can run inside your application without permission hence more prone to th
    3 min read
  • How a Function Returns an Object in JavaScript ?
    JavaScript Functions are versatile constructs that can return various values, including objects. Returning objects from functions is a common practice, especially when you want to encapsulate data and behavior into a single entity. In this article, we will see how a function returns an object in Jav
    3 min read
  • How to create a private variable in JavaScript ?
    In this article, we will try to understand how we could create private variables in JavaScript. Let us first understand what are the ways through which we may declare the variables generally in JavaScript. Syntax: By using the following syntaxes we could declare our variables in JavaScript. var vari
    3 min read
  • How to Declare Multiple Variables in JavaScript?
    JavaScript variables are used as container to store values, and they can be of any data type. You can declare variables using the var, let, or const keywords. JavaScript provides different ways to declare multiple variables either individually or in a single line for efficiency and readability. Decl
    2 min read
  • How to write an inline IF statement in JavaScript ?
    We can write an inline IF statement in javascript using the methods described below. Method 1: In this method we write an inline IF statement Without else, only by using the statement given below. Syntax: (a < b) && (your code here) Above statement is equivalent to if(a < b){ // Your c
    2 min read
  • How to use a closure to create a private counter in JavaScript ?
    A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. Example: Here the inner forms closure with outer. The str variable
    4 min read
  • How to change the value of a global variable inside of a function using JavaScript ?
    Pre-requisite: Global and Local variables in JavaScript Local Scope: Variables that are declared inside a function is called local variables and these are accessed only inside the function. Local variables are deleted when the function is completed. Global Scope: Global variables can be accessed fro
    2 min read
  • Function that can be called only once in JavaScript
    In JavaScript, you can create a function that can be called only once by using a closure to keep track of whether the function has been called before. JavaScript closure is a feature that allows inner functions to access the outer scope of a function. Closure helps in binding a function to its outer
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences