What are advantages of predefining variable in global scope?-Collection of common programming errors

As others have suggested you must read more about variable hoisting in Javascript. I will try to demonstrate it.

function test() {

    var t1 = msg + " hello";  
    console.log(t1); // prints "undefined hello" because msg is undefined
    var t2 = msgx + " hello"; // msgx ReferenceError

    var a = 1;
    var b = 2;
    if (a > b) {
        var msg = 'sample';
    }

}

test();

Here in the example you can see that msg is declared. but it is undefined. On the other hand msgx causes reference error. It is not declared anywhere. So the point is the statement var msg = 'sample'; which comes later in the function inside if braces makes msg a valid variable everywhere in the function. So again declaring msg will give you predefined variable warning.

In javascript only a function can create a scope. Everything declared in a function will be available in the whole function scope even though there are inner braces of other control statements. All the variables declared in different lines inside a function will be hoisted and treated as if declared in the starting line of the function.

Originally posted 2013-11-09 21:09:08.