Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 436
Loktar Avatar asked Sep 22 '11 14:09

Loktar


2 Answers

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

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

like image 100
rlemon Avatar answered Nov 14 '22 23:11

rlemon


You have JSFiddle set to onLoad, so var a is scoped to the onLoad function. Change it to no wrap and you get:

undefined
undefined
Uncaught ReferenceError: baz is not defined
like image 22
Quentin Avatar answered Nov 14 '22 23:11

Quentin