Javascript behavior - function expression vs function declaration - difference

Why the link for the function is not createdf

if ( function f() { } ) {
    console.log( typeof f );
}
// result: undefined 
Run codeHide result

While the assignment / setting variable works fine insideif( )

if ( f = 'assigned' ) {
     console.log( typeof f );
}
// result: string
Run codeHide result

I need to know that what happens in the first case, as the second case works as expected

Can someone explain please?

+4
source share
1 answer

As you put function f() { }in the context of an expression, this is a named function expression, not a function declaration.

, , , f, f (), , .

// Global scope
function a() {
// a is a function declaration and creates a variable called a to which the function is assigned in the scope (global) that the declaration appears in
    function b() {
    // b is a function declaration and creates a variable called a to which the function is assigned in the scope (function a) that the declaration appears in
    }
    var c = function d() {
    // c is a variable in the scope of the function b. The function d is assigned to it explicitly
    // d is a function expression and creates a variable called d to which the function is assigned in the scope (function d) of itself

    };
}
+7

Source: https://habr.com/ru/post/1695489/


All Articles