Skip to main content
  • Home
  • Blog
  • Sandbox

Alvin Pascoe

Website Developer

Alvin Pascoe
Loading.....
  • JavaScript assert() Function
    JavaScript assert() Function
  • Install Homebrew without Xcode
    Install Homebrew without Xcode

JavaScript Memoisation

17th September, 2015

When coding, we should always aim to make our programs as efficient as possible. Memoisation is a technique whereby we speed up expensive computer operations by caching the result...allowing subsequent calls to fetch the result from the cache instead of reprocessing the time-consuming operation.

Below is an example of JavaScript Memoisation in action. Here we're simple calculating whether a number is a prime number. This will be an expensive operation as we're going to iterate through numbers looking for a whole-number factor. When we find a result (true or false), we store it in an array (our cache). Next time the function is run, we check the array for the corresponding result..if it is found, return it...if not, calculate the result, store it in the array and then return it.

Try testing the example below with an input of 6700417 - console.log(isPrime(6700417));.

After the function returns a result, try again. The second time will be considerably faster than the first time!

For a couple of related examples, check out the following GitHub Gist: Simple JavaScript storing and self-memoising function examples.

function isPrime(value){
//Create the cache on the first run through.
//The cache is created as a property of the function.
if(!isPrime.answers) isPrime.answers = {};

//Check the cache for the current value, return it if found.
if(isPrime.answers[value] != null){
    return isPrime.answers[value];
}

//Otherwise, compute result
//1 is never a prime number
var prime = value != 1;

//Run through numbers and check for a whole-number factor.
for(var i = 2; i < value; i++){
    if (value % i == 0){
        prime = false;
        break;
    }
}

//Return the boolean result and assign it to the cache.
return isPrime.answers[value] = prime;
}
  • JavaScript
  • Programming
  • Previous Article: JavaScript assert() Function
    Previous Article: JavaScript assert() Function
  • Next Article: Install Homebrew without Xcode
    Next Article: Install Homebrew without Xcode

Blog Archives

  • December 2019 (1)
  • November 2019 (1)
  • August 2019 (1)
  • May 2019 (1)
  • October 2018 (1)
  • February 2017 (2)
  • January 2017 (3)
  • November 2016 (1)
  • July 2016 (1)
  • January 2016 (1)
More...

Categories

  • Angular
  • CSS
  • Development Environment
  • Drupal
  • Git
  • JavaScript
  • Mac
  • Programming
  • React
  • Tutorial
  • Workflow
  • Home
  • Blog
  • Sandbox
  • Pattern Library
© 2026 Alvin Pascoe
hello{at}alvinpascoe{dot}com
Made by Me, Alvin Pascoe