2

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?

Lev
  • 13,856
  • 14
  • 52
  • 84

2 Answers2

2

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

Geeky
  • 7,420
  • 2
  • 24
  • 50
  • Actually you don't need to pass obj as an argument to the IIFE as the global scope is accessible from inside the function declaration. – Lev Dec 25 '16 at 00:01
0

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?

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206