0

Why is foo a property of window when it's not used or initialized until a few lines later

for(var propName in window) {
    if(propName == 'foo') { //obv defined if its here
        console.log('WTF? Its already a part of window!!');
    }
}
console.log(typeof foo);
var foo = 'bar';

1 Answers1

1

Your code actually look like this one due to var top hoisting.

When you declared the variable globally it is part of this object implicilty. So,your foo variable is part of window object which is refered by this object.

var foo;
for (var propName in window) {
    if (propName == 'foo') { //obv defined if its here
        console.log('WTF? Its already a part of window!!');
    }
}

console.log(typeof foo);
foo = 'bar';

this===window //true in this case
Benjamin Albert
  • 738
  • 1
  • 7
  • 19
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53