JavaScript: Is it okay to give a function the same name as the function expression?

164 Views Asked by At

In JavaScript, if I create a function expression like:

var foo = function foo() {
  return 'Hello world!';
}

Is this okay? Will there be any problems that occur? Or should I do:

var foo = function baz() {
  return 'Hello world!';
}
2

There are 2 best solutions below

0
On BEST ANSWER

The main difference is that in your first example, when inside the function, foo is a shadowed variable, and doesn't refer to the global foo. For example:

var foo = function foo() {
 foo = 1;
}
foo();
console.log(typeof(foo));

outputs 'function' because we have only redefined foo inside the function.

However if you defined the function the second way, foo refers to the global object:

var foo = function baz() {
 foo = 1;
}
foo();
console.log(typeof(foo));

And this will output 'number' since we have modified the global object.

2
On

It depends on what you want. The inner name is local to the function; the outer name is in the outer scope, and is captured by the closure. Thus, if you name your functions differently, you can reassign the outer reference from the inside:

var foo = function baz() {
  return foo;
};
var quux = foo;
foo = 17;
quux(); // => 17

This is not possible when you name the functions differently the same, since the outer variable will not be accessible, shadowed by the inner one. If you want this scenario, then you will need to name them differently. However, I would not say there is any problem in naming the functions either way.

EDIT: Unless you need to support end-of-lifed browsers. Then beware dragons.