var a = function b() {
};
console.log(typeof b); //gives undefined
console.log(typeof a); //gives function
Why the difference in the two outputs?
I understand the difference between function expression and function statement, but not able to understand the output above.
From what I know, javascript makes var a point to the memory allocated to named function b here. In such a case typeof b should also return function but it returns undefined
Any explanations?
-
See kangax.github.io/nfe.user663031– user6630312017年02月25日 13:10:15 +00:00Commented Feb 25, 2017 at 13:10
3 Answers 3
Because the name of a named function expression is scoped to the expression.
var a = function b() {
console.log(typeof b); //gives function
console.log(typeof a); //gives function
};
console.log(typeof b); //gives undefined
console.log(typeof a); //gives function
a();
1 Comment
Why the difference in the two outputs?
You're taking a function expression for a function named b and assigning it to a variable named a. That means a is in scope where the expression occurs, but b is not; it's only in scope within the function. (The whole function, including the parameter list; that last part is only relevant for ES2015+, not ES5 and earlier: You can use b as the value of a default parameter.)
You probably expected b to be in scope where the expression was, because that's true for a function declaration:
function b() {
}
console.log(typeof b);
But this is just a difference in how function declarations and function expressions are handled.
5 Comments
functionWith
function b(){
}
you declare a function called b. This statement has no return value and therefor the return value is undefined.
To declare an anonymous function you have to omit the function name in the declaration, like this:
function(){
};
This one is just a function literal you can assign to a variable like that:
var a = function(){
};