Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Javascript what are closures used for

Javascript what are closures used for

Closure in JavaScript holds the combination of function and the lexical environment within the same function that the lexical environment has been declared. Consider a below example

function Person() {

    var name = 'Rajani'; 
    
    function displayName() { 
    
        console.log(name);
    }
    
    displayName();
}

Person();
// output
// Rajani

Person function declares the variable called a name. And it has one more function called displayName inside called inner function. And the scope of displayName will be available with the function Person. The function displayName has no local variable called as name, but it has a scope to access its parent variable called as the name, this execution model is closure in the javascript.

What is interesting with closure in javascript?
In most of the other programming languages, the variables declared within the function will be available only for execution duration of the same function. Once the execution is been completed then the variable inside the function is no longer available. But the JavaScript still has access to the same variable this makes closure interesting. In other words, a displayName function creates its instance.

function addCounter(x) {
    return function(y) {
    
        return x + y;
    };
}

var add10 = addCounter(10);
var add5 = addCounter(5);

console.log(add10(10)); 
console.log(add5(5)); 
// output
// 20
// 10

Practical example for closure in javascript?
Closure help in where you associate some data with a function that operates on that data. Objects allow you to associate some objects properties with one or more methods.

Why we need closures in javascript?

The closure is very helpful in the event-based application, where you define some behaviour then attach it to the event that is triggered by the user. The behaviour of the code is attached as a callback which is executed in response to the event. Create a file index.html and place the below code and run in a browser

 

<html>
   <head>
      <style>
         body 
         {
         font-family: Helvetica, Arial, sans-serif;
         font-size: 12px;
         }
         h1
         {
         font-size: 1.5em;
         }
         .anchor
         {
         text-decoration: none;
         border: 2px solid blue;
         border-radius: 20px;
         padding: 10px;
         margin: 10px;
         }
         *
         {
             margin: 30px 21px 20px 20px;
         }
      </style>
   </head>
   <body id="id">
      <h1>Closure practical example</h1>
      <h1>Click on the below buttons to change the font size</h1>
      <a href="#" class="anchor" id="size-12">Increase font sie : 12px</a>
      <a href="#" class="anchor" id="size-14">Increase font sie : 14px</a>
      <a href="#" class="anchor" id="size-16">Increase font sie : 16px</a>
      <p> 
         Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      </p>
      <p>
         It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
      </p>
      <script type="text/javascript">
         function makeSizer(size) 
         {
         return function() 
         {
         document.body.style.fontSize = size + 'px';
         };
         }
         var size12 = makeSizer(12);
         var size14 = makeSizer(14);
         var size16 = makeSizer(16);
         document.getElementById('size-12').onclick = size12;
         document.getElementById('size-14').onclick = size14;
         document.getElementById('size-16').onclick = size16;
      </script>
   </body>
</html>

Emulating private methods with closures:
Closure helps to emulate private methods. The below visitor hits function demonstrates the private methods with closures.

var visitorCount = (function() 
{
    var privateVisitorCounter = 0;
    
    // inner function
    function changeBy(val) 
    {
        privateVisitorCounter += val;
    }


    return {
        increment: function() {
            changeBy(1);
        },
        decrement: function() {
            changeBy(-1);
        },
        totalHits: function() {
            return privateVisitorCounter;
        }
    };
})();




console.log(visitorCount.totalHits());
visitorCount.increment();
console.log(visitorCount.totalHits());
visitorCount.decrement();
console.log(visitorCount.totalHits());
visitorCount.increment();
console.log(visitorCount.totalHits());
// output
// 0
// 1
// 0
// 1

The variable privateVisitorCounter can not be accessed outside the function visitorCount. It’s clear that variable privateVisitorCounter can be initialized only once. Whenever called for increment or decrement is happening because of the lexical environment that is created by the inner functions.

If you are not aware with scope in Javascript, read the below points,
Global Scope: The variable declared as globally and the same variable is available for accessing throughout your code.
Function Scope: The variable declared inside a function and it can be accessed within the function itself
Block Scope: The variable declared in a block and those variables are needed in the block.

Also, read What are promises in JavaScript?

5 thoughts on “Javascript what are closures used for

  1. I like what you guys are usually up too. Such clever work and reporting!
    Keep up the terrific works guys I’ve added you guys to my blogroll.

  2. Undeniably believe that which you said. Your favourite reason seemed to be at the web the simplest thing to
    remember of. I say to you, I certainly get annoyed
    while folks consider issues that they plainly don’t recognize about.
    You controlled to hit the nail upon the highest and defined out the entire thing with no need side effect , other folks could take a signal.
    Will likely be again to get more. Thanks

Comments are closed.