Reputation: 12549
I'm just trying to get my head around this function expression.
It seems that if I create a function expression (p
) that seems to contain a function declaration, the function declaration a()
returns undefined.
var p;
p = function a() { return 'Hello' }
typeof p; // returns 'function'
typeof a; // returns 'undefined'
Can anyone explain why this is the case?
And also please let me know if my terminology is off too.
Upvotes: 3
Views: 146
Reputation: 664969
It seems that if I create a function expression (p) that seems to contain a function declaration
No. It is a named function expression, which does not "contain" a function declaration. The name of the function expression is available as an identifier inside the function's scope (pointing to the function itself), and as the nonstandard name
property.
Upvotes: 1
Reputation: 56873
You can think of it as an anonymous function.
The reason that this is valid is because the local function name a
can be used within the function declaration for recursion, but is not valid outside of this scope.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/function
Upvotes: -3
Reputation: 943999
It isn't a function declaration. It is a function expression that happens to have a name. The name does not create a variable, but you can see it on the object
quentin@raston ~ $ node
> var p;
undefined
> p = function a() { return 'Hello' }
[Function: a]
> typeof p; // returns 'function'
'function'
> typeof a; // returns 'undefined'
'undefined'
> p
[Function: a]
> p.name
'a'
>
Upvotes: 5