2

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

I have some Javascript which mostly works except this one function which I can call from some areas but not others. It appears to be a scope issue but I don't know why.

$().ready(function () {
   UpdateElfDisplay(); // <--- Undefined

   $('#Attribute1').change(function () {
      UpdateElfDisplay();  // <--- Works just fine.
   });

   var UpdateElfDisplay = function () {
      // ... some work done here 
   };
 });

As I marked above, the UpdateElfDisplay function works fine when I call it from .change() function but I get an "undefined" if I try to call it when the document is loaded. Can somebody explain why, or direct me to a resource describing this.

Community
  • 1
  • 1
Sailing Judo
  • 11,083
  • 20
  • 66
  • 97
  • Try moving the UpdateElfDisplay function declaration before your first call. – Ram Oct 04 '12 at 17:53
  • @epascarello - Hmm. I can see why some people might consider this a duplicate question because it now looks like the answers are the same. However, I think the question is sufficiently different. For example, "What color is the sky?" and "What color is the ocean?" might have the same answer but aren't duplicate questions. – Sailing Judo Oct 04 '12 at 18:00
  • It is the same answer, just different ways to ask it. lol – epascarello Oct 04 '12 at 18:01
  • Yes. I guess I'm saying the ultimate question and answer are the same, but the question didn't seem the same to me until I saw the answer... if that makes any sense. – Sailing Judo Oct 04 '12 at 18:02

2 Answers2

5

You're calling the function before it's defined, so it doesn't work. The one in the handler is invoked later, so it works

If you use a function declaration, it'll be "hoisted" and will work.

function UpdateElfDisplay () {
  // ... some work done here 
}

The JavaScript interpreter evaluates the declaration form of functions before any expressions are evaluated.


Side note

The reason it's a TypeError and not a ReferenceError is that the var UpdateElfDisplay is actually hoisted similar to the function declaration, but the assignment itself is not hoisted.

This means the variable exists, but it doesn't yet have your assigned value.


Side note 2

Your handler could probably be rewritten like this:

$('#Attribute1').change(UpdateElfDisplay);
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • Well, there is actually more work going on the .change handler, I just abbreviated it to demonstrate my problem. But you answer is very clear now. Thanks. – Sailing Judo Oct 04 '12 at 18:05
4
var UpdateElfDisplay = function () {

Until this line, UpdateElfDisplay has not been iniitalized.

Ram
  • 143,282
  • 16
  • 168
  • 197
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964