Function Expression itself cannot assign Name to another Value
Asked Answered
C

2

4

In the code below:

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

printTest will display "function" instead of "undefined", which makes sense since from my understanding, any variable declarations are always "hoisted" to the top of the execution context (which in this case is function execution context) This makes the function declaration "test()" to be the one that appears later in the current execution context. Now consider this code where I actually assign a value to var declaration "var test =1".

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

Then printTest displays "number" now, which means that the execution context now maintains a different order. Can somebody explain what has actually happened here?

Classless answered 11/6, 2011 at 22:15 Comment(1)
Function declarations don't end with semi-colons, so your ; at the end of the function test line is evaluated as an empty statement which is useless at that position. Therefore, delete that semi-colons.Nazler
M
2

Hoisting separates the actual assignment from the variable declaration. What it's really doing is this:

(function (){
        var test, printTest;
        test = function (){};
        test = 1;//assign value to a variable here
        printTest = typeof test;
        document.write(printTest);
    })();
Marita answered 11/6, 2011 at 22:21 Comment(1)
Maybe var test, test, printTest; would make the point more obvious.Candelariacandelario
E
2

var test only means "Anything called test should be scoped locally". It is undefined only because you haven't assigned a value to it (except you have with function test(){}; which is why you get function and not undefined).

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

Egypt answered 11/6, 2011 at 22:20 Comment(0)
M
2

Hoisting separates the actual assignment from the variable declaration. What it's really doing is this:

(function (){
        var test, printTest;
        test = function (){};
        test = 1;//assign value to a variable here
        printTest = typeof test;
        document.write(printTest);
    })();
Marita answered 11/6, 2011 at 22:21 Comment(1)
Maybe var test, test, printTest; would make the point more obvious.Candelariacandelario

© 2022 - 2024 — McMap. All rights reserved.