2

I'm wondering about named function expressions in javascript, specifically node.

Is there any reason to avoid the following?

var foo = function foo () {};

I really like using function expressions for code organization but I really like function declarations for stack traces. As far as I can tell the above code works, but it just doesn't look right.

Can anyone provide any insight?

ABE: I'm specifically looking for the instance where you are naming a function the same as the variable you are assigning it to.

Function declarations come with the added baggage that you have to have internal functions defined prior to their use in order to avoid jslint warnings and hence your code tends to read last to first which I'm not a fan of.

To get around this you can use function expressions, define your vars at the top and then order your code more or less in the order it is run. However, going this route means your functions are all anonymous unless you name them. Which brings us back to the original question.

Can I name a function declaration that is being assigned to a varable the same as the variable itself.

0

4 Answers 4

3

Named function expressions work in v8 (and therefore node), no problem. Just in old versions of IE, there are problems.

Sign up to request clarification or add additional context in comments.

Comments

1

this is the difference:

// anonymous function expression
var x = function(){};
console.log(x.name);   // "" -> empty string

// named function expression
var x = function foo(){};
console.log(x.name);   // "foo"

// function statement (old thing with function 'hoisting' behavior) 
function foo(){};
console.log(foo.name); // "foo"

You can use any of these. 'Name' is handy when you are writing 'Class' Object or something like that.

Comments

0

var foo = function() {};

function foo() {};

Both should be possible. Combining them shouldn't give you any problems.

Comments

-1

var foo = function foo () {};

is silly because you can do

function foo () {}

There's no reason to use named function expressions over function declarations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.