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?

0

1 Answer 1

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"); };    

    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a bunch, Trevor. Is there a reason/logic behind this difference?
It's just how the JS parser was written. Perhaps this article will be of assistance. net.tutsplus.com/tutorials/javascript-ajax/…. I used to have this great article on how it actually stored the vars, but I am unable to find it. :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.