Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

1.

 $(function () {
       function foo() { return true; }
       log(bar());                        // getting error
       var bar = function() { return true; };   
  });

2.

$(function () {
        function foo() { return true; }
        log(bar());                        // working 
        function bar() { return true; };  
});

in above snippets log is my custom function to log the result.

share|improve this question

closed as off topic by ChrisF Jun 11 '12 at 11:02

Questions on Programmers Stack Exchange are expected to relate to software development within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

    
Please ask coding questions on Stack Overflow. If you create an account there, I'll migrate this question for you –  ChrisF Jun 11 '12 at 11:03

3 Answers 3

In the second, the function bar() is hoisted to the top of your function block (all functions declared in a block using this syntax are hoisted to the top of the block) and thus exists before you call it in log(bar()). In the first, the variable bar is not set to your function until after your call to log(bar()).

share|improve this answer

In your first code block bar is a function variable that obeys scope. In the second code block is a globally declared function because it is not placed inside a scoped variable.

share|improve this answer

In the first, you have called an variable as an function.

long(bar);
var bar=function() {return true;};

try this in first one.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.