The problem is, whether you realize it or not, javascript invisibly moves all var declarations to the top of the scope.
so if you have such a function
var i = 5; function testvar () { alert(i); var i=3; } testvar();
the warning window will contain undefined. because internally it has been changed to this:
var i = 5; function testvar () { var i; alert(i); i=3; } testvar();
this is called "rise." The reason crockford protects var declarations so much comes at the top because it makes the code explicitly compatible with what it is going to do, rather than allowing invisible and unexpected behavior.
Breton Aug 05 '09 at 23:27 2009-08-05 23:27
source share