Search code examples
javascripthoisting

Trying to fully understand JavaScript hoisting


Edit Looks like it was an issue on my part and my usage of jsfiddle :?

Ive been reading a couple of articles on hoisting lately, one is by Nicholas Zakas, and the other is by Ben Cherry.

Im trying to follow the examples and just test on my own to make sure I fully grasp it but Im having an issue mainly with this example,

if (!('a' in window)) {
    var a = 1;
}
console.log(a);

Instead of logging undefined its logging 1. If I am understanding everything correctly, a should be undefined, because it should exist in the window scope due to the var statement being hoisted to the top, so it should not be assigned the value.

But the following is acting as expected,

(function bar(){
    console.log(foo);
    var foo = 10;  
    console.log(baz);
})();

foo is undefined, and baz is not defined. I have a fiddle here with both examples. Really just trying to wrap my head around this. Has something changed since these articles were written maybe? If anyone can shed some light on this it would be appreciated. Im using Chrome 14 when testing.


Solution

  • Change the wrap in the fiddle to no wrap(head)

    http://jsfiddle.net/rlemon/VjCqF/3/