Question

I'm trying to store a reference in my javascript to a page element that will be interacted with frequently and using this code:

var breadcrumbBar = null;
function getBreadcrumbBarElement() {
    if (breadcrumbBar === null) {
        breadcrumbBar = document.getElementById(breadcrumbBarElementId);
    }
    return breadcrumbBar;
}

However, I'm wondering if I can be more terse or idiomatic than this (and as a result improve my javascript more generally...)?

Was it helpful?

Solution

The idiomatic way is to use the logical or operator:

var breadcrumbBar = null;
function getBreadcrumbBarElement() {
    return breadcrumbBar || (breadcrumbBar = document.getElementById(breadcrumbBarElementId));
}

or, to make this a bit more generic:

var elementCache = {}

function getCached(id) {
    return elementCache[id] || (elementCache[id] = document.getElementById(id));
}

OTHER TIPS

Or in order to encapsulate the cache into function:

function getCached(id) {
  if (!getCached.elementCache) getCached.elementCache = {}; 
  return getCached.elementCache[id] || (getCached.elementCache[id] = document.getElementById(id));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top