JavaScript block area vs function

Are the following fragments equal? If not, then what respect?

var x = (function() { ... //a return function(){ ... //b }; })(); 

vs.

 var x; { ... //a x = function(){ ... //b }; } 
+4
source share
2 answers

There is a big difference: in JavaScript, blocks do not invoke a new scope of variables. Therefore, you cannot define private variables in the code block // a . Compare

 var x = (function() { var v = 42; return function(){ return v; }; })(); // v; would yield ReferenceError: v is not defined, so you need to call x 

and

 var x; { var v = 42; x = function(){ return v; }; } // v is 42 here, that not what intended. 
+6
source

One significant difference is that at runtime ...//a x does not exist. Now in your case, in both cases it is undefined , but, generally speaking, it is possible to access the variable x during ...//a , and in the first case it is not.

Otherwise, it is very similar in your circumstances. Indeed, in your case, the code is basically reorganized into a separate function, as in any other language.

0
source

All Articles