1

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 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Do you know any way to auto release instead of nulling every variable ?
@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.
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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.