Skip to: Navigation Content Search


Declaring functions in JavaScript

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.

One Response to “Declaring functions in JavaScript”

  1. Patrick Says:

    As you say, function definitions occur at parse time. Your anonymous function on the other hand is bound to the variable at execution time. As your code is executing sequentially in the example you are trying to use the variable as a function before you’ve bound any function to it.

    It’s important to note the difference between foo and bar below:

    alert(foo);

    alert(bar);
    var bar = function() {};

    The first will error, the second will give you an alert box with undefined.

    You could always do something like this:

    window.setTimeout(function() {
    alert(bar());
    }, 100);

    var bar = function() { return “bar”;};

    There’s also the Function constructor… but nobody uses that (understandably.)

Leave a Reply