Lazy definition function

This has a nice name – a lazy function definition. A lazy function is one that pretends to work but it doesn't really.

It does some work initially and then caches the result. Then on consecutive calls it only returns the pre-computed result, it doesn’t really do anything.

In order to do so, the function redefines itself with a new implementation, one that simply points to the computed result.

function lazy() {
    var result = 2 + 2;
    lazy = function() {
        return result;
    };
    return lazy();
}

lazy(); // 4
lazy(); // 4

Tags: ,

One Response to “Lazy definition function”

  1. nghia Says:

    Hi Stoyan Stefanov
    please answer me a question : What is Lazy definition function used for? and when we use it ?

Leave a Reply