user3651106
user3651106

Reputation: 29

Variable References in Javascript. Referencing globals by and acting on them through a function

I was reading a article on Javascript Performance that was explaining why local variables are far easier to resolve than global ones. The author said they were creating references in the article and then attached this example (the function snippet).

This example has got me confused, i did not know really know how this function was creating a reference. In my mind I think it should be creating an entirely new object.

In my mind I have become so accustomed to seeing the globals being manipulated from within functions that I am unable to resolve how the global is being manipulated by reference in this example, can anyone give me the details.

  function initUI() {
      var doc = document,
          bd = doc.body,
          links = doc.getElementsByTagName("a"),
          i = 0,
          len = links.length;
      while (i < len) {
          update(links[i++]);
      }
      doc.getElementById("go-btn").onclick = function () {
          start();
      };
      bd.className = "active";
  }

Upvotes: 0

Views: 58

Answers (1)

plalx
plalx

Reputation: 43718

In your example, document is a global variable. In theory it's more expensive to resolve a global variable than resolve a variable that lives in the local scope of a function (@RobG pointed out that may not be true in some browsers). Therefore, if you find yourself having to reference a global variable many times, you may consider creating a local reference to that global variable.

E.g. var doc = document;

However, that kind of micro-optimizations are rarely necessary and can probably be considered as premature optimizations. It's far more useful to learn how to optimize DOM-related operations.

Upvotes: 1

Related Questions