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.

4
  • Looks like bikeshedding and/or premature optimization to me. Commented Jun 9, 2018 at 18:46
  • Didn't get it. What you mean, Uwe? Commented Jun 9, 2018 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. Commented Jun 9, 2018 at 18:49
  • 1
    "I know that local variables lives has short lives" - nope, not necessarily, look into closures. Commented Jun 9, 2018 at 20:00

1 Answer 1

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.

answered Jun 9, 2018 at 18:49
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.