Implied Globals

Implied Globals: Any variable you don't declare becomes a property of the global object in JavaScript.

Two examples for demonstration:

1)

function sum(x, y) {
    result = x + y; // implied global
    return result;
}
sum(1,2); // 3
console.log(this.result); // 3
console.log(typeof result); // "number"
delete result; // true
console.log(typeof result); // "undefined"

2)

function foo() {
    // a is local but b is implied global.
    // It's because of the right-to-left evaluation.
    var a = b = 0;
}
foo();
console.log(this.b); // 0
console.log(this.a); // "undefined"
console.log(typeof b); // "number"
delete b; // true
console.log(typeof b); // "undefined"

Yang Zhao

Read more posts by this author.


Comment