Function – declaration vs. expression (JS)

Function declaration

func1(); // works properly
// func2(); // not defined

function func1() {
    console.log("func1");

    func2(); // works properly
    function func2() {
        console.log("func2");
    }
    func2(); // works properly
}

func1(); // works properly
// func2(); // not defined

They are hoisted, which means the declaration is “moved” to the top of the scope.


Function expression

// func1(); // not defined
// func2(); // not defined

const func1 = function() {
    console.log("func1");

    // func2(); // not defined
    const func2 = function() {
        console.log("func2");
    }
    func2(); // works properly
}

func1(); // works properly
// func2(); // not defined

They aren’t hoisted, which means the declaration is NOT “moved” to the top of the scope.