Does a variable declare in JavaScript with var without memory assignment?

Inside object instances, I like to use a closure mechanism to simulate private member variables. For the potential large number of objects created, I donโ€™t need some of the private members, but I have to declare them to be used in closure, for example โ€œoneโ€, โ€œtwoโ€ and โ€œthreeโ€:

var obj=function() { var one; var two; var three; var M=function() { one=5; }; }; 

(Donโ€™t mind that this is actually not a working example of my installation, just demonstrate the use of closure over three vars with M.)

Do var expressions themselves already make memory, or does it depend on whether something really assigns to these vars as "one"?

+7
source share
3 answers

The interpreter should store information about the scope - one = 5 will change the local variable one instead of creating a global variable (which will happen, for example, using four = 5 ). This information must somehow cost some memory. This memory usage also applies before assigning the value one , since the information must be available at the time of assignment.

How much memory it will cost is hard to say, since it differs by one translator. I think this is not enough to worry.

Note that two / three are not used at all, and garbage can be collected in this example. (Actually, you are not exposing M , so in this example everything could be garbage collected.)

+6
source

When declaring a variable without assigning it a value, some memory should still be available, otherwise you will not be able to refer to the variable later in the program. I do not think that this is a noticeable amount of memory, and will not make any difference.

+5
source

When declaring a variable, the memory space is reserved for it and allows you to store or retrieve from this memory the name you selected for the three variables. Such a space is empty until you fill it with a value (two / the tree will remain empty). This is done using an assignment operation. The assignment operation gives the value of a variable.

+4
source

All Articles