Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between function declaration and function expression for my case

Someone Please explain what is going on here.

 var y = 1;
 if (function f(){return 'some text';}) {
     y += typeof f;
 }
 console.log(y);// "1undefined"

if i change it into function expression

 var y = 1;
 if (a = function f(){return 'some text';}) {
     y += typeof a;
 }
 console.log(y);// "1function"
like image 922
pradsdev Avatar asked Nov 14 '18 15:11

pradsdev


2 Answers

The condition of an if statement is always an expression. In the second case its an assignemnt expression that sets the global (!) variable a to a function, in the first case its just a function expression, and the function goes into nowhere (it is not stored anywhere). f is just the name of the function inside of the function itself (for recursion). Therefore f is not defined outside of it.

like image 72
Jonas Wilms Avatar answered Nov 15 '22 10:11

Jonas Wilms


A function declaration creates a variable with the same name in the current scope.

function a() {
    function b() {
    }
}

In the above example, a variable b is created in the scope of a.


A function expression creates a variable with the same name in its own scope.

function a() {
    (function b() {
    })
}

In the above example, a variable b is created in the scope of b but not a.


In your first example (a named function expression), f doesn't exist outside the function so it is undefined.

In your second example (also a named function express), you are explicitly assigning the function to a (an implicit global) so it is defined.

Neither of your examples features a function declaration, despite your question title. Putting the function keyword inside an if () condition makes it an expression just as much as putting it on the RHS of an =.

like image 35
Quentin Avatar answered Nov 15 '22 08:11

Quentin