You know, the variable can actually be declared under the function. But it must be declared before it is used, meaning before the function is called.
I created a test scenario to show what I mean.
I created a textfile called test.html
with the following simple content:
<script type="text/javascript">
var a = "hello"; // <- the declaration of the variable before the function
function b(){ // <- the actual function
a += " world";
alert(a);
}
b(); // <- and here it is called
</script>
If I load this text file in my Firefox4 (with file://$path_to_file/test.html) I get an alert box with the message Hello world
.
Then I changed the order:
<script type="text/javascript">
function b(){ // <- the actual function
a += " world";
alert(a);
}
var a = "hello"; // <- the declaration of the variable under the function
b(); // <- and here it is called
</script>
The result was the same: Hello World
But when I was putting the declaration under the call like this:
<script type="text/javascript">
function b(){ // <- the actual function
a += " world";
alert(a);
}
b(); // <- and here it is called
var a = "hello"; // <- the declaration of the variable under the call
</script>
I got a different result: undefined world
. JavaScript recognizes that it doesn't know what a
could be and so handles it as undefined
.
Of course a sum of numbers could have been interpreted differently from a sum of strings, so I also tested this:
<script type="text/javascript">
function b(){ // <- the actual function
a += 3;
alert(a);
}
b(); // <- and here it is called
var a = "hello"; // <- the declaration of the variable under the call
</script>
The result was: NaN
meaning Not a Number
.
That is all about laziness and tolerance of JS. Your question can of course also be interpreted concerning the scope of variables and functions. But for that there are already 2 answers. Of course, if they are not enough I can also edit a detailed explanation here.