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"
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.
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 =
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With