Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript behaviour - function expression vs function declaration - difference

Tags:

javascript

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?

like image 413
manjeet Avatar asked Mar 06 '23 13:03

manjeet


1 Answers

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

    };
}
like image 197
Quentin Avatar answered Mar 30 '23 13:03

Quentin