Re:JS Adolescence: Change of opinion regarding certain JavaS...
by aufreak3 on Wednesday November 14, 2012 @12:09AM
(#4782101)
I've had the other kind of trouble with this. While I've almost never had trouble with code declaring variables near the site where they are first needed, I've on quite a few occasions missed top-level declarations, perhaps because I carried with me a memory of a declaration done in another function (or something like that) ... resulting in major "global" catastrophes (sorry ;)
While I acknowledge that declaring vars within ifs/whiles and such can lead to misunderstanding, declaring vars close to the site of first use at the top-level block of a function has never resulted in a bug for me. This approach also diffs better.
It's also just bad form because of how people write Javascript, for example if you have an unfortunately long nested function with a variable declaration toward the bottom with a common name, say 'width' and later add that variable name a level up in scope and then think to use it in your function because you forgot or didn't know you had a var statement declaring width somewhere in that function you'll have fun staring into the abyss when this runtime error eventually presents itself.