Global variable


#1

Let's talk about an important concept: scope. Scope can be global or local.

Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global.

For example:

var globalVar = "hello";

var foo = function() {
    console.log(globalVar);  // prints "hello"
}

//okay i understand that but in this one :  
var my_number = 7; //this has global scope

var timesTwo = function(number) {
    my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
// how the heck is "my_number "a global variable, how am i suppose to identify what is an global variable ?

#2

You can determine the scope of a variable by where it is declared. globalVar, foo, my_number and timesTwo are all created on the main scope and therefore are global. to this scope and all its sub scopes like for example the interior of foo and timesTwo. If you would declare a variable in foo by e.g. var test; then this variable would be local to foo, meaning you could not access it from the main scope but it behaves global to all sub scopes of foo (if you would nest functions inside each other).

A special case that is called shadowin appears if you for example declare a local variable that has the name of a global variable. For example if you would add a var here:

var my_number = 7; //this has global scope

var timesTwo = function(number) {
    var my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
}

By adding the var you declare a new variable which has the same name as the global one but which is completely independent from it, so if you change the inner my_number variable the outer one would not realize it. The reason why this is called shadowing is because now the inner my_number is occupies the name therefore you can't reach the outer one although it is global it's kind of in the shadown of the inner one.

Hope this makes it a little clearer.


#3

How does the var keyword work?
I have noticed that if I declare a variable like this:

var b=1

I sometimes will get a different result than if i just did this:

b=1

This is the program that I wrote:

b=1 //If I use the var keyword here this program doesn't work. Why?
var loop = function()
        { while(b<4)
	        {console.log("I'm looping!");
	        b++
	        }
        };

loop();

I know I am ahead but I came back because I realized I did not truly understand this lesson.


#4

var creates a local variable in the current scope where as omitting the var leads to the creation of a global variable. This might sound tempting but it can be a real problem if you don't intend it to be that global. So the rule of thumb is as local as possible as global as necessary. And what error do you get for your snippet because the var should be totally fine there.