3

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?

manjeet
  • 1,497
  • 10
  • 15

1 Answers1

7

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

    };
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @NinaScholz — Each function defines its own scope (and there is also the global scope). Named function expressions create a variable with the same name as the function inside themselves, which is useful for creating recursive functions. (In ES6 scope gets more complicated with the addition of block level scope to the language, but that's irrelevent here as only function scope is involved). – Quentin Mar 28 '18 at 20:21
  • no, i mean the outside scope of the function. (the expression nature of the function, where it looks like an expression is a very good explanation.) – Nina Scholz Mar 28 '18 at 20:24
  • Maybe you should add a reference that explains the difference between function expressions and function declaration. – Rashad Saleh Mar 28 '18 at 20:26
  • @NinaScholz — There are (potentially) lots of scopes that are outside the function. It isn't available in any of them though. – Quentin Mar 28 '18 at 20:28