JavaScript closures in brief

What’s a closure

Well every javascript programer knows that a variable defined in javascript file with the var declaration is global into all javascript code.

var a = 12;
console.log(a);

that code prints 12 into the console.

Note: console object is visible in Firefox and Safari, but not in IE, and here’s used just for the test!

Here comes the closures

Let’s assume I’ve two javascript files.

file1.js:

var a = 12;

file2.js:

a = 13;

Than obviously if I print out the variable a in file2.js after that line, I’ll have the value of a equal to 13, and this will be the value of the variable a from the file1.js, because that’s obviously the same variable.

Now let’s make it “private” using closures. First define an anonymous function in file1.js

file1.js:

(function() {
    var a = 12;
})();

With that you define an anonymous function and the ending () you’re invoking that function. Now if you change the above code like that:

file1.js:

(function() {
    var a = 12;
    console.log(a);
})();

the javascript console in FF will print 12, but if you have the code in file2.js another variable with the same name that will be another variable. Let’s merge the two files for better example.

file.js:

var a = 13;

(function() {
    a = 12;
    console.log(a);
})();

console.log(a);

that code will print first 12 and than 13, and that makes clear what the closure function does. Without the closure it will look like this:

file.js:

var a = 13;

var f = function() {
    a = 12;
    console.log(a);
}
f();

console.log(a);

and that will print twice the value of a which is 12.

How to export variables, functions and objects from a closure

Simply by assigning the variables, objects, etc. to appropriate variables in the window object, like that:

file.js:

var a = 13;

(function() {
    a = 12;
    console.log(a);
    window.b = a;
})();

console.log(a);
console.log(b);

now you’ll have first printed 12 from the closure function, than 13 which is the value of the global variable a, and than again 12 which is the variable b, which equals to the closure a, and it’s exported with the help of the window object.

Leave a Reply

Your email address will not be published. Required fields are marked *