Gourav Kumar Shaw
Gourav Kumar Shaw

Reputation: 117

Where is the variable stored?

Every time we execute the function foo(), we are creating a new object out which is getting returned. Every such out object has two properties getName and setName, both are functions. These functions remember their scope in which they were defined and so these functions are always able to access their own copy of variable name.

My question is where actually is the variable name stored in memory for each out object? It must be stored inside some object (if I am not wrong).

1) Surely it is not stored in the object out, else it would have been accessible using dot notation.

2) Also, it is not stored in the function object foo. Had it been x.setName("JavaScript") would have affected the value of y.getName() but it is not so.

function foo(){
    var name=""; 
    out = {
      getName: function(){return name;}, 
      setName: function(newName){name = newName}
    }; 
    return out;}; 

var x = foo(); 

var y = foo();

Upvotes: 1

Views: 222

Answers (2)

Quentin
Quentin

Reputation: 944216

My question is where actually is the variable name stored in memory for each out object?

You have no way to tell and (probably) no reason to care. The JavaScript engine manages memory for you.

It must be stored inside some object (if I am not wrong).

The JavaScript engine might not even be written in an OO-language.

1) Surely it is not stored in the object out, else it would have been accessible using dot notation.

No. JavaScript manages scope separately from the properties of objects.

2) Also, it is not stored in the function object foo.

Again. No.

The value of the variable is stored in the variable.

The JavaScript engine manages the storage of that variable in memory.

You can't inspect the memory assignments from inside your JavaScript program, no API is provided to do that.

Upvotes: 1

ssc-hrep3
ssc-hrep3

Reputation: 16089

JavaScript has a function scope. This means, that every function call has its own set of variables. If you declare a variable in a function by using the word var, this value is uniquely stored in this function instance. If you are returning out with access to this function instance, the variable won't be cleared by the garbage collector and still be available as opposed to if no reference is pointing to the variable anymore.

You can find more information about the scopes in JavaScript here on StackOverflow.

Upvotes: 2

Related Questions