manjeet
manjeet

Reputation: 1517

javascript behaviour - function expression vs function declaration - difference

Why no reference is created for function f

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

Whereas assigning/setting variable works fine inside if( )

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

I need to know that whats going on in the first case as the second case is working as expected

Can anybody explain, please?

Upvotes: 3

Views: 126

Answers (1)

Quentin
Quentin

Reputation: 943193

Since you have put function f() { } in expression context, it is a named function expression and not a function declaration.

That means that while it creates a function, and that function has the name f, it creates the variable with the name f in the scope of the function (itself) and not in the scope in which the function is created.

// 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

    };
}

Upvotes: 7

Related Questions