2

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?

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
Rahul Arora
  • 4,503
  • 1
  • 16
  • 24

3 Answers3

6

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();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    To be 100% precise, there are two scopes involved. The first is the scope of the entire function expression; the second is that between the curly brackets. The scope of the name is the former. In other words, the following is valid, if useless: `a = function b(arg = b) { };`. –  Feb 25 '17 at 13:06
2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-1

With

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(){

};
Psi
  • 6,387
  • 3
  • 16
  • 26