3
var bar = function foo() {
  foo = 1;
  return foo;
};
bar(); // returns function foo()

Why is this happening? I expect this to return 1.

jetru
  • 1,964
  • 4
  • 16
  • 24
  • Isn't that a syntax error? Can you name an anonymous function like that? – Thilo Mar 12 '15 at 02:56
  • Well, if it's a syntax error, why is my Firefox accepting that language? – jetru Mar 12 '15 at 02:57
  • @Thilo this is JS, a bunch of (possibly) bad things are technically legal. This is a legal thing to do. It doesn't really make much sense though... both `foo` and `bar` will reference the same function. – Sumner Evans Mar 12 '15 at 02:59
  • No, bar will represent what the function declaration returns. – jkd Mar 12 '15 at 03:35

3 Answers3

3

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;
};
Community
  • 1
  • 1
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
2

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.

Read more on MDN.

lvarayut
  • 13,963
  • 17
  • 63
  • 87
  • `var bar = function foo(){}`... Can you explain how this "named anonymous function" syntax works? – Thilo Mar 12 '15 at 02:59
  • 1
    @Thilo See this SO question: http://stackoverflow.com/questions/3854141/naming-an-anonymous-function. – Sumner Evans Mar 12 '15 at 03:01
  • 1
    @Thilo, yes, this named function expression is very useful when you have some errors in your function because the compiler could tell you the exact function caused the error. – lvarayut Mar 12 '15 at 03:05
2

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

Community
  • 1
  • 1