4

Are following snippets exactly equal? If no what is the deference?

var x = (function() {
    ... //a
    return function(){
        ... //b
    };
})();

vs.

var x;
{
    ... //a
    x = function(){
        ... //b
    };
}
Ali Shakiba
  • 20,549
  • 18
  • 61
  • 88
  • @JohnS please don't paste code into the title like that. Post your code into the body. – JohnP Apr 30 '11 at 11:23
  • @JohnP You are right but your title is too generic, it's like "What's the problem with my code?" – Ali Shakiba Apr 30 '11 at 11:24
  • @JohnS but that is what you're asking. Pasting the code into the title does not make it readable. Feel free to come up with a better problem statement for your question – JohnP Apr 30 '11 at 11:25
  • @JohnP Have you seen: http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – Ali Shakiba Apr 30 '11 at 11:31
  • @JohnS That's 3 years old. I've only been active for a couple of months. Also that question title is much more readable than what you had put up. Like I said before, please do update your question if you have a better title :) It just needs to be clear and readable – JohnP Apr 30 '11 at 11:37
  • @JohnP I changed it, what now? – Ali Shakiba Apr 30 '11 at 11:39
  • @JohnS well, nothing. You've already marked this question as answered. Now it just helps other people with the same question – JohnP Apr 30 '11 at 11:41

2 Answers2

6

There is a major difference: In JavaScript, blocks don't induce a new variable scope. Therefore, you can't define private variables in the // a code block. Compare

var x = (function() {
    var v = 42;
    return function(){
        return v;
    };
})();
// v; would yield ReferenceError: v is not defined, so you need to call x

and

var x;
{
    var v = 42;
    x = function(){
        return v;
    };
}
// v is 42 here, that's not what's intended.
phihag
  • 278,196
  • 72
  • 453
  • 469
0

One major difference is that at the time of executing ...//a , x doesn't exist. Now in your case, in both cases it is undefined but generally speaking it's possible to access x variable during ...//a while in the first case it's not.

Otherwise in your circumstances it's pretty same. After all in your case the code is basically refactored into a separate function just like in any other language.

neebz
  • 11,465
  • 7
  • 47
  • 64
  • 2
    One more thing: `{var z = 1;}` will create a variable z in the window namespace, while `(function(){var z = 2;}())` will not pollute the global namespace. That's why the function option is preferred – Dan Manastireanu Apr 30 '11 at 11:28