"Krinkle" posted a comment on MediaWiki.r107407. URL: http://www.mediawiki.org/wiki/Special:Code/MediaWiki/107407#c28612
Commit summary for MediaWiki.r107407: [mediawiki.js] function order * define before call * Follows-up r107402, r107405 Krinkle's comment: Regarding the variable declarations on top: I have to admit I never invested much time in C, however I do know a fair bit about how JavaScript works and this is how JavaScript works whether we like it or not. And the quality of code tends to raise when programs are written the way the language they are written in works, not the way other languages the programmer likes work. Prior to execution, JavaScript hoists all variable declarations within a function to the top of the function (block scope doesn't exist). So, as examples: <pre> function foo(){ console.log( x ); // Throws exception: ReferenceError: x is not defined } function bar(){ console.log( x ); // No exception, variable is already declared, just set to "undefined" var x = 5; } // bar() is actually quux() function quux(){ var bar; console.log( bar ); // No exception, variable is already declared, just set to "undefined" bar = 5; } </pre> Now in the above example it may seen trivial, but try the following example (based on example from "''[[JSPERF|Crockford on JavaScript - Act III: Function the Ultimate]]''") <source lang="javascript"> var doStuff = function (foo) { for (var i = 0; i < foo.length; i += 1) { var bar = foo[i]; for (var i = 0; i < bar.length; i += 1) { var quux = bar[i]; } } } </source> The above is an infinite loop. So declaring them on top in my opinion: * Prevents re-using variables causing weird situations like the infinite loop * Gives quick overview of which variables are used in a function * Is what JavaScript will do internally anyway _______________________________________________ MediaWiki-CodeReview mailing list mediawiki-coderev...@lists.wikimedia.org https://lists.wikimedia.org/mailman/listinfo/mediawiki-codereview