Javascript’s Lazy vs Eager Function Execution

by | Jul 4, 2020 | 0 comments

function repeater(count) {
    return function allTheAs(){
        return "".padStart(count,"A");
    };
}

var A = repeater(10);

A(); // Outputs: "AAAAAAAAAA"

Why would we decide to call a function lazily?

PRO: The function might do some expensive computations and we are not sure that the function will ever be called, a good solution would be to run it lazily.

function repeater(count) {
  var str = "".padStart(count,"A");
    return function allTheAs(){
      return str;
    };
}

var A = repeater(10);

A(); // Outputs: "AAAAAAAAAA"
A(); // Outputs: "AAAAAAAAAA"

Having the benefits of both worlds

I’ve got another question for you, is there a way for us to change the code so that the function would do the work only once and we don’t have to do the work unless its been asked for?

function repeater(count) {
  var str;
    return function allTheAs(){
      if ( !str ){
        str = "".padStart(count,"A");
      }
      return str;
  };
}

var A = repeater(10);

A(); // Outputs: "AAAAAAAAAA"
A(); // Outputs: "AAAAAAAAAA"

Functional Programming Aspects

We’ve closed over a function that has a dynamic variable called str
(red functional programming flags going off), at the beginning the variable str is undefined and later we change its value to cache the result.

function repeater(count) {
    return memoize(function allTheAs(){
        return "".padStart(count,"A");
    });
}

var A = repeater(10);

A(); // Outputs: "AAAAAAAAAA"
A(); // Outputs: "AAAAAAAAAA"
  • Will it be called with the same input?

Let’s finish with a clear definition of what is a pure function call

A pure function call is a function that we can take its returned value and replace any other call to that function with that value without breaking any of our application code.

IF YOU GOT ANY VALUE SHARE 😄