katboo
katboo

Reputation: 55

Newbie: Making sense Javascript closure example on MDN

I'm very new to Javascript and I have been reading about closures on MDN. While I understood the first two code snippets on that link, I am confused by the syntax used in the third example that I have copied here.

    var getCode = (function(){
         var secureCode = "0]Eal(eh&2"; 

         return function () {
             return secureCode;
         };
     })();

     getCode();    // Returns the secureCode

What is the purpose of wrapping the outer function within parentheses followed by empty parentheses and a semi-colon? What does this syntax mean or what does it serve? Why not write it as follows instead?

    var getCode = function() {
         var secureCode = "0]Eal(eh&2"; 

         return function () {
             return secureCode;
         }
    };

    getCode();    // Returns the secureCode

Upvotes: 0

Views: 91

Answers (2)

Alexus
Alexus

Reputation: 952

In other words you are encapsulating the secure code variable to a CONST. It can't be written to and thus altered, yet it's available through the getter to read from.

Upvotes: 0

aebabis
aebabis

Reputation: 3715

The point of the example is that secureCode is like a private variable. After the function in parenthesis has executed, secureCode isn't in scope and so cannot be written to; but the returned function still has access to the variable and can be used as a getter.

Upvotes: 1

Related Questions