Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In the Google tutorial for implementing Google+ sign-in in Flask application, I discovered that the developer often uses an awkward way of executing JavaScript code:

Instead of doing

var a = foo(bar);

I see this:

var a = (function() {
  return foo(bar);
})();

What is the reason to do it the weird way?

share|improve this question

marked as duplicate by pduersteler, Tibos, Quentin, Sirko, ling.s Feb 4 '14 at 8:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
can you provide direct example. it depends on the situation –  Vlad Nikitin Feb 3 '14 at 13:07
    
There's no reason to use that syntax there, and it doesn't appear on the page you link to. Could you link to the actual example so we can see the context? –  Quentin Feb 3 '14 at 13:09
    
Oh, ok, so it's just not to leave garbage of once needed but now obsolete variables behind. –  Passiday Feb 3 '14 at 13:13
    
@Quentin the actual code in the tutorial is very large and thus too specific to be included in the question. –  Passiday Feb 3 '14 at 13:15

3 Answers 3

up vote 1 down vote accepted

This is a poor example. Consider the following:

var a = (function(){
    var ret = {};
    ret.test = "123";
    function imPrivate() { /* ... */ }
    ret.public = function() { imPrivate(); }
    return ret;
})();

a will contain the varible test and the function public, however you can not access imPrivate. This is the common way to handle public vs private variables;

See What exactly is the point of this function construct? Why is it needed? for more info.

share|improve this answer

The closure function is used to encapsulate some of the attributes / methods in the function. Much like the private / public principle from other languages.

You can find more on this topic here under Module Pattern

share|improve this answer
var a = (function() {
  return foo(bar);
})();

In this case this is really unnecessary, but this is not wrong and this is not throw error.

But IIF some times uses like module pattern:

var a = (function() {
  /* some other code in own scope */
  return foo(bar);
})();

In this case IIF just a module which exports something outside.

share|improve this answer
    
Thanks, I updated it. –  Passiday Feb 3 '14 at 13:11
1  
I update my answer too :) –  Pinal Feb 3 '14 at 13:12

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