Should I use a variable that takes an HTML element as global or local?

5
function message (className, text) {
    /*Esta variável*/var message = document.getElementById("message");/*Esta variável*/
    message.className = className;
    message.innerHTML = text;
    setTimeout(function () {
        message.innerHTML = "";
    }, 2000);
}  

I'm just going to use this variable within this function, but I believe that if I leave it as a local every time I call this function JavaScript will have to access the HTML again to fetch this element, how global the element will already be caught. What is more performative?

    
asked by anonymous 12.07.2017 / 13:32

2 answers

4

Variables declared inside functions are erased from memory after the execute function. So in terms of memory management the variable inside the function is better. Another issue that is good to keep in mind is not to overload global space with variable names that can accidentally be overwritten.

There is still another possibility, with an IIFE, which leaves the local variable but does not need to go to the DOM each time the function executes that is

var message = (function(el) {
  return function(className, text) {
    el.className = className;
    el.innerHTML = text;
    setTimeout(function() {
      el.innerHTML = "";
    }, 2000);
  }
})(document.getElementById("message"));

So the element / object is in the memory of the function and not global (which is better if it is permanently stored in memory), it does not pollute the global space and you do not have to go to the DOM every time the function is executed .

    
12.07.2017 / 13:43
4

See Global variable in JavaScript and Why using global variables is not a good practice? .

Then always use local variable. Although this is a case for thinking if global is not advantageous. If you are sure that HTML will never change, but you have to be sure, that will never change, and you can not always guarantee that, so you can use some techniques to avoid this processing. I do not know if it pays, I do not know if it's worth the risk.

There is a technique called memo . You can do this in JavaScript by holding the private object variable through use of this .

    
12.07.2017 / 13:45