tags:

views:

24

answers:

2

Example code below;

function a() {
    var a = 123;
    //some stuff
    b();
}

function b() {
    //some stuff
}

a();

So my question is whether the variable 'a' is in memory while b() is executed ?

Thank you.

+2  A: 

Yes it is. It's not in b()'s scope, but it is in memory.

You can't just magically delete objects withing a()'s scope. You could manually delete a; if you wouldn't need it anymore, but the best and most reasonable way to do this is by calling them one after the other instead of nested calls:

function a() {
    var a = 123;
    //some stuff
}

function b() {
    //some stuff
}

a();
b();

If there is not a quick way to do this, consider refactoring your code a bit

Gabi Purcaru
Do you know any way to auto release instead of nulling every variable ?
Ozgur
@Ozgur: It should get released automatically at a somewhat random point after `a` completes. Javascript is garbage collected, which means that if you don't have a handle to a variable anymore, it will eventually get cleaned up.
Merlyn Morgan-Graham
@Gabi, the `delete` operator doesn't really work for this case as you recommend. With a `FunctionDeclaration`, like `a` in your example, `delete a;` will fail, because the identifier is bound to the *variable object* as *non-deletable*, (`{DontDelete}` in ECMAScript 3, or `[[Configurable]] = false`) moreover, in the new ECMAScript 5 Edition Strict Mode, deleting an identifier, (like `delete a;`) will cause a `SyntaxError`, this was made due the large misunderstanding of this operator... More info: [Understanding `delete`](http://perfectionkills.com/understanding-delete/).
CMS
thanks @CMS! [three characters to go]
Gabi Purcaru
+1  A: 

This is going to be both implementation specific, and program specific. It will depend on the exact javascript platform it is running on, things like the system memory size, and how much code/how many variables were allocated before a() was run.

You can't rely on it being deallocated before or during b(), because garbage collection is non-deterministic.

In most cases, it will probably stay in memory.

Merlyn Morgan-Graham