Last Updated: February 25, 2016
·
1.099K
· robert52

Cache function's return value in javascript

Sometimes you need to do some heavy stuff in a function and maybe you need to run it once and afterwards you just want to use the output, but without creating another variable.

function foo() { 
    var results = 'hello there';

    if (foo.cache) {
        console.log('from cache');
        results = foo.cache;
    } else {
        console.log('first run');

        // long dirty stuff

        foo.cache = results;
    }

    return results;
}

//calling foo() for the first time
foo(); // => 'first run' and will return 'hello there'

//calling it for the second time
foo(); // => 'from cache' and will return 'hello there'

Enjoy!

2 Responses
Add your response

No declare 'cache' var?

over 1 year ago ·

You can access it from 'foo.cache'

over 1 year ago ·