Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript global variable scope

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.

like image 930
randomor Avatar asked Dec 13 '22 05:12

randomor


1 Answers

Only variables declared without var become 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 recommended for these reasons (off the top of head):

  • Variable resolution starts at the most local and goes toward looking in the global namespace, making it slower. Much slower in certain browsers.
  • You tend to eventually have naming conflicts by polluting the global namespace. One of the worst offenders would be, say, 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 recommend 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.

like image 81
Eric Wendelin Avatar answered Dec 22 '22 00:12

Eric Wendelin