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
    };
}
7
  • @JohnS please don't paste code into the title like that. Post your code into the body. Commented Apr 30, 2011 at 11:23
  • @JohnP You are right but your title is too generic, it's like "What's the problem with my code?" Commented Apr 30, 2011 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 Commented Apr 30, 2011 at 11:25
  • @JohnP Have you seen: stackoverflow.com/questions/336859/… Commented Apr 30, 2011 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 Commented Apr 30, 2011 at 11:37

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.