Javascript does not have block scope, but it does have function scope. A variable defined anywhere within a function is visible everywhere within the function.
function foo(){ console.log("a:",a);//variable a is visible here but it is still undefined console.log("f:",f);//variable f is visible here but it is still undefined var a=1; var f=function(){ console.log("f"); } } foo();
So, it is best to declare all of the variables used in a function at the top of the function body. If we check the angularjs source code, we find it does exactly the same way.
// at the top, it declares all the global variables var $$scope = '$scope', $boolean = 'boolean', $console = 'console', $length = 'length', $name = 'name', $object = 'object', ... // in each function, it also declare the variables at the top function forEach(obj, iterator, context) { var key; if (obj) {... ...