Loading ...
Sorry, an error occurred while loading the content.

Re: function declaration style implications

Expand Messages
  • theblargoner
    Yes, there is precisely the subtle difference you noticed. Functions declared with the function declaration syntax are evaluated (i.e. defined) in an execution
    Message 1 of 2 , May 29, 2009
    • 0 Attachment
      Yes, there is precisely the subtle difference you noticed. Functions declared with the function declaration syntax are evaluated (i.e. defined) in an execution context before any code is run in that context. So your first example works. When assigning the anonymous function to a variable manually, the variable is only defined when that line of code is run.

      As far as I know, this is the only difference between the two methods.

      (A book that covers this well is Nicholas Zakas's "Professional JavaScript" 2nd ed.)

      John

      --- In ydn-javascript@yahoogroups.com, "sbillmassie" <sbillmassie@...> wrote:
      >
      > I had always thought that:
      > function hello() {
      > return "hello";
      > }
      > was equivalent to:
      > var hello = function() {
      > return "hello";
      > }
      >
      > But I noticed that this code works:
      > <script type="text/javascript">
      > alert(hello());
      > function hello() {
      > return "hello";
      > }
      > </script>
      > but this code causes an error (in FF "hello is not a function"):
      > <script type="text/javascript">
      > alert(hello());
      > var hello = function() {
      > return 'Hello';
      > }
      > </script>
      >
      > So there must be a subtle difference. I feel like this is addressed somewhere in the trusty Rino book, but I haven't been able to find it.
      >
      > Can someone explain the underlying differences to me?
      >
      > Thanks,
      > Bill Massie
      >
    Your message has been successfully submitted and would be delivered to recipients shortly.