So I hear that variable in js that initialized without a "var" will be global. so:
$(document).ready(function(){
function foo(){
//since i'm not using "var", will this function bee global?
}
var bar = function(){
//is this the better way to declare the function?
}
})
If it is global, why I can't access it in the console. If it's not global, and it's scope is in the function, will omitting "var" cost some performances? Thanks.
So I hear that variable in js that initialized without a "var" will be global. so:
$(document).ready(function(){
function foo(){
//since i'm not using "var", will this function bee global?
}
var bar = function(){
//is this the better way to declare the function?
}
})
If it is global, why I can't access it in the console. If it's not global, and it's scope is in the function, will omitting "var" cost some performances? Thanks.
Only variables declared without var
bee global, this does not apply to functions.
You can, however, declare foo like so:
foo = function() {}
and it should be global.
Omitting var
is generally not remended for these reasons (off the top of head):
for(i = 0; i < arr.length; i++)
(note the lack of var
)You might want to declare functions using var
due to a language feature called hoisting
BTW, if you do choose to declare functions with var
, I remend you do so this way:
var foo = function foo() {}
because it gives the function a "name" instead of being treated as an anonymous function, which will help with debugging. Most people do not do this and declare using function
, I believe.