Reputation: 365
I'm trying to build skills in using local variables. To make a variable local, I declare it within the function that I want to use it in, right?
But if I'm using this function very often, won't I be declaring this variable over and over? Is this OK or not?
For example if I have a function like this:
function myFunction() {
var myVariable;
// some code that requires myVariable
}
...I'm going to be declaring myVariable every time. Will this cause space in memory to be set aside for myVariable every time the function is called? Is there a way around this?
Upvotes: 3
Views: 143
Reputation: 7916
Yes thats a local variable i.e cannot access it outside this scope.
This is fine to do and in fact one of the recommended practices.
Yes, memory is used each time its called but then it is cleared/garbage collected when the function is done executing(assuming no other leaks).
One more thing though, you could change the var
to a let
for even better block scoping... although not necessary in this very simple case.
Upvotes: 5
Reputation: 1362
Basically, it does not take more execution time, if you declare it in your function scope.
However, declaring it scoped in a function can save memory, because after executing the function, the variable is unneccessary and the garbage collector deletes it on its next execution (probability). If it's not scoped, it is still there until the execution of the script ends. So, you have over the whole runtime a variable in memory, which is maybe unneeded.
To help the browser, you could use ECMAScript 2016 let
keyword for variable declaration, because there you define a clear scope and the browser can better optimize your code.
Also, using the const
keyword instead of var
coould save a little bit of memory. Because with this you specify that is value is not changed anymore and this fact leads to less memory consumption.
Upvotes: 0
Reputation: 165
Maybe you should have a quick look on javascript best practice: Here is one of many possible links
There is also stated that you should not use Global Variables. You should declare the variable always in this Scope.
You will not run in any Memory-problems. The garbage collector will handle it for you. But to be sure how the garbage collector is working in Javascript another link of many possible here Garbagecollector explanation javascript
And I would recommend to use let instead of var another link for more information: let explenation
Upvotes: 0
Reputation: 36620
Every function call creates another element on the stack. When the element of the stack is popped of all the local variables which are not used anymore are garbage collected. Therefore it is better to declare variables locally if you want, cause you will actually save memory.
Upvotes: 1