JavaScript: Can I give a function with the same name as a function expression?

In JavaScript, if I create a function expression like:

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

      

This is normal? Will there be any problems? Or do I need:

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

      

+3


source to share


2 answers


The main difference is that in the first example, when inside a function, foo

is a shaded variable and is not global foo

. For example:

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

      

outputs 'function'

because we only redefined the foo function inside the function.



However, if you have defined a function the second way, it foo

refers to the global object:

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

      

And this will output 'number'

, since we changed the global object.

+3


source


It depends on what you want. The internal name is local to the function; the outer name is in outer space and is captured by the closure. This way, if you name your functions differently, you can reassign the external reference from within:

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

      



This is not possible if you call the functions otherwise the same, since the outer variable will not be accessible, shaded by the inner one. If you want this script, you will need to name them differently. However, I would not say there are any problems when naming functions anyway.

EDIT: Unless you need support for extended browsers. Then beware of dragons.

+2


source







All Articles