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 become 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
varbecome global, this does not apply to functions.You can, however, declare foo like so:
and it should be global.
Omitting
varis generally not recommended for these reasons (off the top of head):for(i = 0; i < arr.length; i++)(note the lack ofvar)You might want to declare functions using
vardue to a language feature called hoistingBTW, if you do choose to declare functions with
var, I recommend you do so this way: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.