The function expression itself cannot name another value

In the code below:

(function (){ function test(){};//"function" var test;//"undefined" var printTest = typeof test; document.write(printTest); })(); 

printTest will display a "function" instead of "undefined", which makes sense because, as I understand it, any variable declarations always "go up" at the top of the execution context (which in this case is the context of the function's execution) This makes the declaration of the function "test ()" one that appears later in the current execution context. Now consider this code, where I actually assign a value to the declaration var "var test = 1".

 (function (){ function test(){}; var test=1;//assign value to a variable here var printTest = typeof test; document.write(printTest); })(); 

Then printTest now displays a "number", which means that the execution context now supports a different order. Can someone explain what really happened here?

+4
javascript hoisting
source share
2 answers

A lift separates the actual assignment from the variable declaration. This is true:

 (function (){ var test, printTest; test = function (){}; test = 1;//assign value to a variable here printTest = typeof test; document.write(printTest); })(); 
+2
source share

var test means only "Everything called a tag must be locally local." It is undefined only because you did not assign a value to it (except that you have function test(){}; so you get a function , not an undefined ).

In the second example, function test(){}; still assigns a function to it, but then var test=1; overwrites this with 1 . You use typeof after assigning it 1 , so it reports that it is a number.

+2
source share

All Articles