Tuesday, November 26, 2013

Variable Scope & Function Scope

According to the book Javascript The Definitive Guide, The scope of a variable is the region of your program source code in which it is defined. A global variable has global scope; it is defined everywhere in your Javascript code. On the other hand, variables declared within a function are defined only within the body of the function. Open up your javascript interactive console and let's do some experiments.

js> var a_global_var = 'global';
js> function local_scope_demo(){
var a_local_var = 'local';
}
js> a_global_var
"global"
js> a_local_var
typein:25: ReferenceError: a_local_var is not defined

As we can see here, we can access global variable outside the function body but not local variable, because it is only accessible within the body of the function.

From the example above, we can actually see another feature of javascript, called Function scope: variables are visible within the function in which they are defined and within any functions that are nested within that function. 

Compare the two code snippet of Java and Javascript.

public class HelloWorld {

    public static void main(String[] args) {
        for(int i=0;i<10;i++){
                System.out.println("i in the for loop is "+i);
        }
        System.out.println("i out of for loop is "+i);
    }
}

Compile and run this Java code and you'll get the following error. That's because Java has block scope, which means each block of code within curly braces has its own scope, and variables are not visible outside of the block in which they are declared.

cannot find symbol
symbol  : variable i
location: class HelloWorld
 System.out.println("i out of for loop is "+i);
                                            ^
1 error

However, the following javascript code will run successfully all because Javascript is a function-scope language.

function function_scope_demo(){
for(var i=0;i<10;i++){
console.log(k);
}
console.log(k);  // k is 10
}