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

Asked

Viewed 265 times

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 will only use this variable within this function, but I believe that if I leave it as a location each time I call this function Javascript will have to access the HTML again to search for this element, and if I leave it as a global element the element will already be caught. What is more performatic?

2 answers

4


Variables declared within functions are deleted from memory after the function runs. So in terms of memory management the variable within the function is best. Another good point to bear in mind is to not overload the global space with variable names that can accidentally be overwritten.

There is also another possibility, with an IIFE, that leaves the local variable but does not need to go to the DOM every time the function performs that is

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

Thus the element/object remains in the function memory and not global (which is better still to be stored in memory permanently), does not pollute the global space and it is not necessary to go to the DOM to search every time the function is executed.

  • Thank you very much for the answers, it helped a lot because I didn’t know these ways of doing it, but now I’m going to use.

4

Behold Global variable in Javascript and Why using global variables is not a good practice?.

So always use local variable. Although this is a case to think about if global is not advantageous. If you’re sure that HTML will never change, but you have to be sure, that never will change, can not always guarantee this, so it is possible to use some technique to avoid this processing. I don’t know if it pays, I don’t know if it’s worth the risk.

There is a technique called memoisation. It is possible to do this in Javascript by maintaining the private object variable through the use of this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.