Skip to content Skip to sidebar Skip to footer

When Is Creating Local Variables In Functions Already Better?

Let's say I have a total of 6 global variables, and I were to call them in a function. If I were to call them each 3 times is it already better to create a local variable in the f

Solution 1:

If i were to call them each 3 times is it already better to create a local variable in the function, would it run the function faster?

Not to any perceptible degree. The reason you should avoid global variables is because they can conflict with any 3rd party utilities you're running, can conflict with any plugins your browser is running, and frankly make the code harder to read.

If your function needs 6 variables, then create those variables inside of the function.

If you have 3 functions that all share the same 6 variables, then you have an object that desperately would like to be created -- refactor your code to reflect that.

So something like this:

var a = 1,
    b = 2,
    c = 3;

function f1(){
    //use a, b, and c
}

function f2(){
    //use a, b, and c
}

Would become something like this:

var obj = {
    a: 1,
    b: 2,
    c: 3,
    f1: function(){
       alert(this.a);
    },
    f2: function(){
       //use this.a, this.b, and this.c
    }
};

And of course if you want a, b, and c to be private to the object, you can get creative with closures:

var obj = (function(){
   var a = 1,
       b = 2,
       c = 3;
   return {
      f1: function(){
         alert(a);
      },
      f2: function(){
         //use a, b, and c
      }
   };
})();

Post a Comment for "When Is Creating Local Variables In Functions Already Better?"