1
I’m making a code that a very large function, where I declare some local variables with const
and let
. To improve his reading I’m dividing this function into several small functions. So I ended up declaring within the scope of these functions, the variables again. What used to be, for example, 5 local variables have now multiplied into 50 or more local variables within these functions.
What’s best?
1 - Declare these variables with let
and const
only once outside the scope of the functions. And then go only by assigning new values to these variables within the functions (except for const
).
let thisHelp = null;
let thisSymbol = null;
let thisText = null;
function myFunction() {
thisHelp = SceneManager._scene._helpWindow;
thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
thisText = Eli.Param.HelpWindows.menuText
thisHelp.x = 100;
};
function myFuntion2() {
thisHelp = SceneManager._scene._helpWindow;
thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
thisText = Eli.Param.HelpWindows.etc;
thisHelp.x = 100;
};
2 - Do the same, declare and assign a value to variables only within the functions.
function myFunction() {
const thisHelp = SceneManager._scene._helpWindow;
const thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
const thisText = Eli.Param.HelpWindows.menuText
thisHelp.x = 100;
};
function myFuntion2() {
const thisHelp = SceneManager._scene._helpWindow;
const thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
const thisText = Eli.Param.HelpWindows.etc;
thisHelp.x = 100;
}
3 - I’m worried a lot and this for Javascript is not a question of performance. I mean, I can do it anyway.
If you want to check the performance between two alternatives, where the result is not obvious, measure the time taken to execute each option (v.g use console.time() and console.timeend()). Apart from that, the problem with your example is that people who work with you or depend on your code will look at the first case, see three global variables without a clear need and already go to be very sorry.
– user142154
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site
– Maniero