Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function scopes and global variables

Tags:

javascript

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:

  1. Why is window.foo undefined? Aren't all global variables attached to the window object by default?

  2. 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/

like image 969
Johan Avatar asked Apr 25 '13 17:04

Johan


People also ask

What is the scope of global variable?

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.

What is a function scope variable?

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() {

Can global variables be used in a function?

Global variables can be used by everyone, both inside of functions and outside.

What are the 3 three places of scope variables?

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.


1 Answers

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 original foo 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.

like image 55
Felix Kling Avatar answered Oct 02 '22 01:10

Felix Kling