Tuesday 10 May 2016

Hide variable from console access - Javascript Closures and self executing functions

Background

I came across javascript closure when I was searching solution for an interesting question - can variable be private in javascript. Let me give an example to demonstrate this further. Consider following Javascript - 


<script>
var counter = 0;

function increment() {
    counter++;
    console.log('After increment counter : ' + counter);
}

function decrement() {
    counter--;
    console.log(' After decrement counter : ' + counter);
}
</script> 

Now from console in your browser try to access counter variable. You should be able to access it. You can also try to print counter value after executing increment and decrement methods from console.

Couple of notes before we proceed to see the output on console.
  1. In above code counter is a global variable.
  2. In a web page global variables belong to window object. So you can also access it using window.counter.
  3. Global variables can be accessed/changed by all scripts in a page.
  4.  A local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code.
  5. Global and local variables with the same name are different variables. Modifying one, does not modify the other.  
  6. Variables created without the keyword var, are always global, even if they are created inside a function.

Now the question is we don't want to expose counter variable. What can we do? Closures to the rescue.

Javascript closure

Now see the javascript code below - 

<script>

var increment, decrement, printCounter;

(function () {
    var counter = 0;
    increment = function() {
        counter++;
        console.log('After increment counter : ' + counter);
    };
    decrement = function() {
        counter--;
        console.log(' After decrement counter : ' + counter);
    };
    printCounter = function() {
        console.log('counter : ' + counter);
    };
})();

</script>

Now repeat above operation. You cannot access counter variable now. Since it is define inside the closure it's scope is limited to that. functions on the other hand are global, so those you can use.


Noticed the following syntax?

(function(){
    //Bunch of code...
})();


It's called self executing function. It is executed only once when page loads.



So A closure is a function having access to the parent scope, even after the parent function has closed. 
If you just have one method you can also do something like -

 var increment = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

increment();
increment();
increment();
// the counter is now 3 



Related Links

t> UA-39527780-1 back to top