0

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

In JavaScript, I can define a function and assign it to a variable:

var myVar = function myFunc(){};

or define the function standalone:

function myFunc(){};

What are the use cases for the first approach?

Community
  • 1
  • 1
AdamNYC
  • 19,887
  • 29
  • 98
  • 154

1 Answers1

4

functions declared to variables are not hoisted to the top of the scope

function run() {

   fn1(); // logs "hi"
   fn2(); // error

   function fn1 () { console.log("hi"); }
   var fn2 = function () { console.log("hi again"); };    

}

See this previous related answer. Are named functions or anonymous functions preferred in JavaScript?

This will end up looking similar to this after the parse runs through it

function run() {

       function fn1 () { console.log("hi"); }
       var fn2;

       fn1(); // logs "hi"
       fn2(); // error


       fn2 = function () { console.log("hi again"); };    

    }
Community
  • 1
  • 1
Trevor
  • 11,269
  • 2
  • 33
  • 40
  • Thanks a bunch, Trevor. Is there a reason/logic behind this difference? – AdamNYC Jan 20 '13 at 18:17
  • It's just how the JS parser was written. Perhaps this article will be of assistance. http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/. I used to have this great article on how it actually stored the vars, but I am unable to find it. :( – Trevor Jan 22 '13 at 16:20