Which is better:
var foo = 0,
fnFoo = function (bar)
{
"use strict";
// Do stuff
};
$(document).ready(function ()
{
"use strict";
fnFoo(foo);
});
OR
$(document).ready(function ()
{
"use strict";
var foo = 0,
fnFoo = function (bar)
{
"use strict";
// Do stuff
};
fnFoo(foo);
});
The difference is the location of the variable/function declarations. In this case, assume that only the ready event needs to use foo and fnFoo.
If only the
readyevent needs it, then put it inready. That’s the whole point of encapsulation. Restrict access to variables as much as possible to reduce bugs in code. What happens if you accidentally declare anotherfooorfnFooby accident later on?Not only that, but it makes your code more understandable. It means that you know exactly what each variable is used for and where.