Skip to content

Use of closure in JavaScript | Basics

  • by

The advantage of closure in JavaScript is that it allows you to bind a variable to an execution context. JavaScript closures are defined as inner functions and are used to access variables and parameters of the outer function even after the outer function has returned.

var closedIn = {};

var f = function(){
   closedIn.blah = 'blah'; // closedIn was just "closed in" because I used in the function, but it was defined outside the function.
}
// Define the closure
function multFn() {
  var mult = 9;
  return function(val) {
    mult = mult * val;
    return mult;
  }
}
  
// Use the closure
var mult = multFn();
console.log(mult(18)); //164

A closure has three scope chains –

  1. Has access to its scope, i.e., the variable defined within its curly braces
  2. Has access to the variables of the outer functions
  3. Has access to the global variables

Use of closure in JavaScript

Simple example code. Since “closure” is just a way of saying that a function always retains its original variable scope, there are many ways you can take advantage of that.

Using private variables and methods

<!DOCTYPE html>
<html>
<body>

  <script>
    // Define the closure
    var rentPrice = function(initialRent) {
      var rent = initialRent;

    // Define private variables for the closure
    return {
      getRent: function() {
        return console.log(rent);
      },
      incRent: function(amount) {
        rent += amount;
        console.log(rent);
      },
      decRent: function(amount) {
        rent -= amount;
        console.log(rent);
      }
    }
  }

  var Rent = rentPrice(8000);

  // Access the private methods
  Rent.incRent(2000);
  Rent.decRent(1500);
  Rent.decRent(1000);
  Rent.incRent(2000);
  Rent.getRent();

</script>

</body>
</html>

Output:

Use of closure in JavaScript

Maintaining the state between each function call

Closures help in maintaining the state between function calls without using a global variable.

(function() {

var multFn = function multiply() {
	// This variable is local to
	// the closure and holds
	// its value inbetween
	// multiple calls
var mult = 9;
return function(val) {
	mult = mult * val;
	return mult;
}
};

var mult = multFn();
	
// Call the method
// multiple times
console.log(mult(2)); //18
console.log(mult(3)); //54
console.log(mult(5)); //270
}());

Source: geeksforgeeks.org

Here’s a practical example of how closures can be used to create a private counter:

function createCounter() {
  let count = 0;

  return {
    increment: function() {
      count++;
    },
    decrement: function() {
      count--;
    },
    getCount: function() {
      return count;
    }
  };
}

const counter = createCounter();

counter.increment();
counter.increment();
counter.decrement();

console.log(counter.getCount()); // Output: 1

In above example, createCounter returns an object with three methods (increment, decrement, and getCount), each of which forms a closure over the count variable. This encapsulation allows us to maintain a private counter that cannot be accessed or modified from outside the createCounter function.

Do comment if you have any doubts or suggestions on this Js closure topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading