Search code examples
javascriptfunctionhoisting

What is difference between hoisting var x = 3 and var x


Consider the two following snippets

function x(){}
var x = 3;
console.log(typeof x) //"number"

This happens because function declarations are hoisted first.

function x(){}
var x;
console.log(typeof x) //"function"

I expect the type to be undefined because var x; creates a variable with undefined value.


Solution

  • var x declares the variable xbut doesn't assign anything to it.

    If you did set its value to undefined, then that would be undefined:

    function x(){}
    var x = undefined;
    console.log(typeof x) //"undefined"

    So what you made in your example is just

    var x;
    function x(){}
    

    While in my example it becomes

    var x;
    function x(){}
    x = undefined;