Understanding closures in Javascript - Javascript weekly
Tags: showdev, webdev, tutorial, beginners
Published: 2019-07-06 20:39:23

---
title: Understanding closures in Javascript - Javascript weekly
published: true
description: Understanding closures in Javascript - Javascript weekly
tags: showdev,webdev,tutorial,beginners
series : javascript
canonical_url: https://cloudnweb.dev/2019/07/understanding-closures-in-javascript-javascript-weekly/
---
For regular updates, subscribe to weekly newsletter, <a href="http://eepurl.com/gvbr7j">Weekly Updates</a>.

<!-- wp:paragraph -->
<p>In this article, we will see what closure is and why do we need something like closure, Understanding closures in Javascript - Javascript weekly</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Previous Article :  <a href="https://cloudnweb.dev/2019/06/understanding-generators-in-javascript-javascript-weekly/">https://cloudnweb.dev/2019/06/understanding-generators-in-javascript-javascript-weekly/</a> </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is Closure?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In simple terms, Closure is nothing but a function which is defined inside another function. the closure has access to all the local variables, outside function variables and global variables.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":925} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/07/closure.png" alt="" class="wp-image-925"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Problem Statement</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To understand this in a better way, consider the following result of code.</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>Problem Statement</li></ol>
<!-- /wp:list -->

<!-- wp:code -->
<pre class="wp-block-code"><code>let name = "Ganesh";

function getMyName() {
  console.log("Name is "+name);
}

name = "Mani";

getMyName(); //what will be the output here?</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>This kind of scenario is common in web development(front-end as well as backend). we will define a function and call the function later some point of time.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>2. Problem Statement </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function getMyName() {
  let name = "Ganesh";

  return function() {
    console.log(name);
  };
}

let name = "Mani";

// create a function
let myname = getMyName();

// call it
myname(); // What will it show? </code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>To understand this concept, first, we need to understand the concept of <strong>Lexical Environment</strong></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Lexical Environment</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Lexical Environment is nothing but maintaining the state of the particular function and its outer environment state, variables.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":934} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/07/lexical_env.png" alt="" class="wp-image-934"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Every inner function will have a local variable, inner function can also access the parent function variable and global variable.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Maintaining the scope of the particular function is nothing but a Lexical Environment.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Coming back to Problem Statements...</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now, if we come back to the problem statements, the problem statement #1 would return the value as "Mani" </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Because ,The value gets updated since we have defined it as Global Variable. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, in Problem statement #2,  we have defined a function called <strong>getMyName()</strong>. inside the function, we have defined a variable called <strong>name</strong> which is nothing but a parent function variable.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>we are returning a function from the <strong>getMyName()</strong> function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, if we define the same variable called <strong>name</strong> in the global context and execute the <strong>getMyName()</strong>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>it won't change the value of it. because <strong>getMyName()</strong> returning a function which is nothing but a <strong>Closure</strong> will hold the variable state and value for the particular environment</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://output.jsbin.com/qikuginowe">https://output.jsbin.com/qikuginowe</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> javascript first look inside the inner function, then it will look in the parent function. finally, it will go look in the global variables.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Closure - Practical Implementation</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Using Closure instead of objects</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you are familiar with OOPS concepts, you will know that concept of "<strong>this</strong>", which will refer the <strong>context </strong>of the class</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's try to write a function using OO concept and then we will see how we can rewrite that with Closures.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function User(){

  this.firstname = "John";

  this.lastName = "Robert";
}

User.prototype.getFirstName = function getFirstName() {
  console.log(this.firstname);
}

User.prototype.getLastname = function getLastname() {
 console.log(this.lastName);
}

User.prototype.showFullName = function showFullName() {
   console.log(this.firstname+" "+this.lastName);
}

module.exports = User;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>we are creating a function called user and add the function <strong>getFirstName</strong>, <strong>getLastName </strong>and <strong>showFullName </strong>for the particular user function and access the function variable with <strong>this </strong>keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To call this particular function we need to create an new instance of it and call the particular function</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>
let User = require('./user');

let data = new User();
data.showFullName();
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>it will show me something like "<strong>John Robert</strong>"</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, let's see how we can rewrite this with <strong>Closures</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function User() {

  let firstName = "Will";

  let lastName = "Smith";

  return { 
   getFirstName : function () {
    console.log(firstName);
  },

   getLastName: function () {
      console.log(lastName);
    },

    showFullName :function () {
      console.log(firstName+" "+lastName);
    }
  }
}

module.exports = User;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>we are defining a user function like we did before, then instead of binding the function. we are returning those function from the parent function <strong>user</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Note </strong>: return functions are nothing but closures.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, if i want to call this function , we have to do something like</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//using Closure in Javascript

let userClosure = require('./user_closure');

let closureresult = userClosure();

closureresult.showFullName()</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>it will return "<strong>Will Smith</strong>" as output.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is one of the real-time use cases where can try to implement <strong>Closures </strong>instead of going with <strong>this </strong>keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Quiz :</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Try to solve this problem and comment your result in this post and explain me how it works.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function doIncrement(){
  let counter = 0;

  return function(){
    counter ++;
    return counter; 
  }
}

let increment = doIncrement();

console.log(increment());
console.log(increment());
console.log(increment());
//What is the result ?</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>That's it for this week. try to implement this in a real time usecases, so that you can grab the concept out of it.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Reference :</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>we will see some other features of javascript in upcoming articles.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Until then, <strong>Happy Coding</strong> :-)</p>
<!-- /wp:paragraph -->