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!
Written by Robert Onodi
Related protips
2 Responses
No declare 'cache' var?
over 1 year ago
·
You can access it from 'foo.cache'
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#