var bar = function foo() {
foo = 1;
return foo;
};
bar(); // returns function foo()
Why is this happening? I expect this to return 1.
var bar = function foo() {
foo = 1;
return foo;
};
bar(); // returns function foo()
Why is this happening? I expect this to return 1.
If you want it to return 1, you need to write it like this:
var bar = function() {
foo = 1;
return foo;
};
LVarayut's answer is actually right, you are writing over foo which is in the global namespace. This version declares a local variable foo.
var bar = function() {
var foo = 1;
return foo;
};
It's because you have defined foo variable twice, so if you want to return 1, you could change the name of your function to anything else:
var bar = function baz() {
foo = 1;
return foo;
};
bar(); // returns 1
Or you could define a local variable:
var bar = function foo() {
var foo = 1;
return foo;
};
bar(); // returns 1
EDIT: Here is the answer of your question. The name of a named function expression becomes a local variable and can be only accessed inside the function expression. There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned.
Here is a similar question that describes the same behavior...
Function and variable with the same name
And a linked article that describes what is happening...
http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting