Javascript - Closure

About

Closure in Javascript

The most common usage of closure in JavaScript is the module pattern.

Closures have access and can update their outer variables. Closures store their outer variables by references, not by copying their values. Updates are then visible to any construct that have access to them.

Example

Basic

A function is an object that creates a context and retains its state.

JavaScript provides a convenient literal syntax for constructing closures, the function expression.

function add(increment) {
  
  var x = increment;

 // The function expression is below after the return keyword
  return function(y) {
           return y + x;
  };
  
}

var incrementBy2= add(2);
var incrementBy5= add(5);

console.log( incrementBy2(1) );
console.log( incrementBy5(10) );

Variable sharing

The function set and get properties are closures that have access to the same val variable.

function obj() {
    var val = undefined;
    let get = function() { return this.val; }
    return {
        set: function(val) { this.val = val; },
        get: get,
        add: function(val){this.val = this.get() + val;}
    };
}
var o = obj();
console.log(o.get());  
o.set(10);
console.log(o.get());  
o.add(10);
console.log(o.get());  





Discover More
How to create a Debounce Function in Javascript?

A debounce is a function that: will wrap a callback function willnot let the callback function execute for each event will let the callback function execute only when a certain amount of time...
Javascript - Function Expression (Anonymous function)

A Reference/Operators/functionFunction Expression is just an function in the form of an expression stored generally in a variable that you execute by adding its signature ([param,[, param,[..., param]]])...
Javascript Function Method
Javascript - Functions

Functions functionalities in Javascript. A function in Javascript is a variable that’s given a reference to the function being declared. The function itself is a value (as an integer or an array) that...
Javascript - Module Pattern

This article shows classic design pattern with ECMAScript on how to organize javascript code with a structure that make possible to: get input return output and hide the implementation from the...
Javascript - Variable (var)

Everything in JavaScript is an object, and can be stored in a variable. In javascript, a variable may then contains a function as value. See function expression. You can then also return a function from...



Share this page:
Follow us:
Task Runner