Javascript - Closure

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - 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.


3 - Example

3.1 - 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) );

3.2 - Variable sharing

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

function obj() {
    var val = undefined;
    return {
        set: function(val) { this.val = val; },
        get: function() { return this.val; }
var o = obj();

web/javascript/es/closure.txt · Last modified: 2019/02/16 17:40 by gerardnico