Lev
Lev

Reputation: 15734

Where is stored a variable declared in an IIFE?

In the following example

var foo = "bar;

(function () {    
    var hello = "world";
    debugger;
}());

the variable foo is declared in the global scope, thus it becomes a property of window and the expression window.foo returns "bar".

If I stop at the breakpoint in the iife and type hello in the terminal, it returns world.

But on which object is the variable hello stored in?

Upvotes: 2

Views: 219

Answers (2)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

Global scope variables are a syntactic sugar of adding a property to the global object window or global in NodeJS: var a = 11; is the same as window.a = 11;.

How local variables are stored in memory is a concrete JavaScript runtime implementation detail. I wouldn't mind about how's stored since it has no interest in a high level language like JavaScript. They're just variables like in any other old or modern programming language.

Maybe you'll find this other Q&A a good resource to learn more about JavaScript scoping: What is the scope of variables in JavaScript?

Upvotes: 0

Geeky
Geeky

Reputation: 7496

It will have local scope limited to that anonymous function

unless specified it will not associated with any object.In your code it exists independently as hello itself and will not be accessible out side that function

var foo = "bar;

(function () {

    var hello = "world";
    debugger;

}());

If you want it to be associated with any object you could do it as

var foo = "bar";
var obj={};

(function () {
  obj.hello="world";
console.log(obj.hello);
})()
console.log(obj.hello);

Hope this helps

Upvotes: 2

Related Questions