Declaring functions in JavaScript Thursday, May 8th, 2008
Well, here’s a little tip for you if you didn’t know already. Some people say that there are a couple of ways of declaring functions in JavaScript and you can go to town doing one or the other (depending on your tastes) because they do precisely the same thing.
Well they do and they don’t.
Tell me why this will work:
<html>
<head>
<script type="text/javascript">
noodles();
function noodles() {
alert("Do you like noodles?");
}
</script>
</head>
</html>
And not this:
<html>
<head>
<script type="text/javascript">
noodles();
var noodles = function() {
alert("Do you like noodles?");
}
</script>
</head>
</html>
The second example will return our favourite word: undefined.
Maybe obvious to you, but not to me when I first got on the bandwagon. You see the browser will look at all function declarations (that is, the function in the first example) first and think, “Hey, these might be useful!” and then proceed to store them in a little hidey hole for use later. Then it will go on and do everything else. So when the browser encounters a call to a function it already knows what to do.
In the second example, we’re just assigning a function to a variable, which is great, but the browser has to know about it before we execute. In other words the execution must come after the variable declaration. It’s like trying to do this:
alert(noodles);
var noodles = "I love noodles!";
It’s just something to keep in mind.
