var foo = '1',
bar = '2';
console.log(foo, bar, window.foo); //1, 2, undefined
(function(foo){
console.log(foo, bar); //2, 2
})(bar);
I have two trivial questions regarding the code above:
Why is window.foo
undefined? Aren't all global variables attached to the window object by default?
Why is foo ===
2 inside of the closure? I know that I'm passing the original bar
with the alias foo
, which is 2
, but outside of the function scope foo
is still 1
. And as far as I know, the original foo
can be accessed from inside of the closure as well. Is the "new foo" prioritized since it's passed as an argument to the IIFE?
http://jsfiddle.net/GbeDX/
In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.
Function Scope Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var , let and const are quite similar when declared inside a function. They all have Function Scope: function myFunction() {
Global variables can be used by everyone, both inside of functions and outside.
A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters.
Why is
window.foo
undefined? Ins't all "global" variables automatically attached to the window object?
Yes, global variables become properties of window
, but the code is not run in global scope in your fiddle. It is run in the load
event handler (see the second checkbox on the left hand side, it says "onLoad"). Here it is run in global scope: http://jsfiddle.net/GbeDX/1/
Why is
foo === 2
inside of the closure? [...] And as far as I know, the originalfoo
can be accessed from inside of the closure as well.
No, it can't. The parameter foo
shadows the variable foo
. If it is a global variable though, you can access it with window.foo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With