javascript function variable scope

A block in a function such as if, switch, while, for, do and try introduces a scope in other languages such as Java. That means variables declared in the the block are not visible outside the block. For example, the Java code snippet below tries to use the variable i and ifV declared in the for and if blocks, and the java compiler will throw error: cannot find symbol because those two variables are only visible within the block it was declared.

public class Hello{
    public static void test(){
        for(int i=0; i<2; i++)
        {
            System.out.println(i);
        }
        if(true)
        {
            int ifV = 2;
        }
        System.out.println(i); //This line will cause the compiler to throw error
        System.out.println(ifV); //This line will cause the compiler to throw error
    }

    public static void main(String args[]){
        test();    
    }
}

In JavaScript, there is only function scope and blocks do not introduce a scope. Variable declared anywhere in a function is visible everywhere in the function. In this javascript code snippet, the variable i is declared in the for block and the ifV is declared in the if block, but they are visible outside the for and if blocks.

function varTest() {
    for (var i = 0; i < 3; i += 1) {
        console.log("loop: " + i);
    }
    if(true) {
        var ifV = 2;
    }
    console.log(i); //This is same variable declared in the for block
    console.log(ifV); //This is the same variable declared in the if block
}
varTest();

It is recommended to declared variables inside the block if those are meant to be short lived within the blocks in programing languages with block scope. Since javascript does not introduce block scope, it will be better off to declare all the variables that are needed in the function at the top of the function. So it won’t trick developers(with other block scope programming experiences) to think that the variable is only available inside the block it’s declared. The above javascript function will be more readable like this

function varTest() {
    var i, ifV;
    for (i = 0; i < 3; i += 1) {
        console.log("loop: " + i);
    }
    if (true) {
        ifV = 2;
    }
    console.log(i); //This is same variable declared in the for block
    console.log(ifV); //This is the same variable declared in the if block
}

varTest();

Search within Codexpedia

Custom Search

Search the entire web

Custom Search