Mantvydas Binderis
Mantvydas Binderis

Reputation: 30

JavaScript variables - best performance

Probably this is dumb question, but I cant find the best answer for it.

Imagine if you have js file something like this:

    //Home page rules
    (function() {

       //Header rules
       (function() {
         function myFunction1(){...}
       }());

       //Main section rules
       (function() {
         function myFunction2(){...}
       }());

    }());

And you need to use same variables in each function.One function is for animating elements on the page when page loads, and another function is for animating menu. I know that global variables should be avoided, I know that local variables has short lives - they are created when the function is invoked, and deleted when the function is finished (probably this is better performance).

QUESTION: What is the best practice and better performance: declare variables once at the top (inside home page rules) or duplicate (repeat your self) same variables in each of these functions?

Hope you get the point I am asking.

Upvotes: 0

Views: 53

Answers (1)

Ben
Ben

Reputation: 244

It depends a lot on the use case. If you are going to declare it over and over again a local variable would not be very efficient, but if you are not going to use it a lot a local variable would probably be better. Declaring a variable takes processing power but it does not take as many resources to sustain it. Keep in mind that these are minor changes and will only stack up in extreme cases. If you are going to run a function over and over again, I would use global variables so that you don't have to re-create them over and over again.

Upvotes: 1

Related Questions