Neat JavaScript trick

I have been reading Secrets of the JavaScript Ninja and learned an new idea. John Resig showed how to cache DOM elements by creating a cache inside of a function. He refers to this as a self-memoizing function and there is an example on page 75. Here is his example:

function getElements(name) {
  if (!getElements.cache) getElements.cache = {};
  return getElements.cache[name] = getElements.cache[name] || 

I can  already think of where I can use this to improve performance on a website.

Leave a Reply

Your email address will not be published. Required fields are marked *