Javascript global variable scope

So, I heard that a variable in js initialized without "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's global, why can't I access it in the console. If it is not global and its scope is in a function, then omits the "var" cost of some performances? Thanks.

+4
source share
1 answer

Only variables declared without var become global; this does not apply to functions.

You can, however, declare foo as follows:

 foo = function() {} 

and it must be global.

Lowering var usually not recommended for these reasons (from the top of the head):

  • The variable resolution starts from the local one and goes to the search in the global namespace, which makes it slower. Much slower in some browsers.
  • You typically have name conflicts, polluting the global namespace. One of the worst offenders will be, say, for(i = 0; i < arr.length; i++) (note the lack of var )

You might want to declare functions with var because of a language function called hoisting

By the way, if you decide to declare functions with var , I recommend that you do this as follows:

 var foo = function foo() {} 

because it gives the function a "name" instead of processing an anonymous function, which will help with debugging. Most people do not, and declare using function , I suppose.

+13
source

Source: https://habr.com/ru/post/1392753/


All Articles