Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does declaring a variable in JavaScript with var without assignment consume memory?

Tags:

javascript

Within instances of objects I like to use the closure mechanism to simulate private member variables. For a potential large number of created objects I don't need some of the private members though, but I have to declare them for them to be used in the closure, like "one", "two" and "three" here:

    var obj=function()
    {
        var one;
        var two;
        var three;

        var M=function()
        {
            one=5;
        };
    };

(Don't mind that this is not actually a working example of my setup, it's just to demonstrate the use of the closure over the three vars with M.)

Do the var statements themselves already consume memory, or does that depend on actually assigning something to these vars like with "one"?

like image 917
Wolfgang Stengel Avatar asked Jan 07 '12 11:01

Wolfgang Stengel


People also ask

How much memory does a variable take in JavaScript?

Each boolean and number variable takes 8 bytes of memory.

What happens if we declare a variable * without * the VAR let keyword *?

If you declare a variable, without using "var", the variable always becomes GLOBAL.

Why you should not use VAR in JavaScript?

This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.

Can I declare a variable in JavaScript without VAR?

Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword. The variables declared without the var keyword becomes global variables, irrespective of where they are declared. Visit Variable Scope in JavaScript to learn about it.


1 Answers

The interpreter has to store information about scope - one = 5 will change the local variable one instead of creating a global variable (which would happen with e.g. four = 5). This information must cost some memory somehow. This memory usage also applies before assigning a value to one, because the information has to be available at the time you're assigning.

How much memory it will cost is difficult to say since it differs per interpreter. I guess it isn't enough to worry about.

Note that two/three are not used at all and may be garbage collected in this example. (Actually, you don't expose M either, so everything may be garbage collected right away in this example.)

like image 123
pimvdb Avatar answered Oct 19 '22 21:10

pimvdb