0

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.

  • Looks like bikeshedding and/or premature optimization to me. – Uwe Keim Jun 09 '18 at 18:46
  • Didn't get it. What you mean, Uwe? – Mantvydas Binderis Jun 09 '18 at 18:48
  • 1
    Global, but some would prefer them nested for debugging. You need to measure the cost. If you need to do an async fetch each time to get the variable values, then a single declaration is far better for performance. Assuming the get isn't costly, then global would be the most performant. – Dan Jun 09 '18 at 18:49
  • 1
    "*I know that local variables lives has short lives*" - nope, not necessarily, [look into closures](https://stackoverflow.com/q/111102/1048572). – Bergi Jun 09 '18 at 20:00

1 Answers1

1

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.

Ben
  • 244
  • 1
  • 14