shrewdbeans
shrewdbeans

Reputation: 12549

JavaScript - Why is this function declaration created in a function expression "undefined"?

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

Answers (3)

Bergi
Bergi

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

samjudson
samjudson

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

Quentin
Quentin

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

Related Questions