Search code examples
javascriptfunctionvarhoisting

Hoisting with var


Why in the first case it will be printed that x is a function and not undefined?

(() => {
    var x

    function x() {}

    console.log(x)
})()

> ƒ x() {}

(() => {
    var x = 1

    function x() {}

    console.log(x)
})()

> 1

Solution

  • This just happens because of how JavaScript works with hoisting. Functions with function VARIABLENAME() {} are brought up right under the variable's "existence" calls, and the variable changing values stays in its place, but is relatively moved down because of the function being moved up.

    First set

    (() => {
        var x
    
        function x() {}
    
        console.log(x)
    })()

    // This gets converted to:
    (() => {
        var x // This variable exists
    
        x = function x() {} // Ya know that variable called x? well its a function
    
        console.log(x)
    })()

    2nd set

    (() => {
        var x = 1
    
        function x() {}
    
        console.log(x)
    })()

    // This gets converted to:
    (() => {
        var x // the variable x exists
    
        x = function x() {} // Functions are moved to the top, under variable declarations
        
        x = 1 // x is now the value 1
    
        console.log(x)
    })()