in ECMAScript

ECMA-262-3 in detail. Chapter 6. Closures.

Read this article in: Russian, French.

Introduction

In this article we will talk about one of the most discussed topics related to JavaScript — about closures. The topic in fact is not new, and was discussed many times. However we will try to discuss and understand it more from a theoretical perspective, and also will look at how closures are implemented in ECMAScript.

Two previous chapters devoted to scope chain and variable object are recommended for reading first, since in this chapter we will use discussed earlier topics.

General theory

Before the discussion of closures directly in ECMAScript, it is necessary to specify a number of definitions from the general theory of functional programming.

As is known, in functional languages (and ECMAScript supports this paradigm and stylistics), functions are data, i.e. they can be assigned to variables, passed as arguments to other functions, returned from functions etc. Such functions have special names and structure.

Definitions

A functional argument (“Funarg”) — is an argument which value is a function.

Example:

function exampleFunc(funArg) {
  funArg();
}

exampleFunc(function () {
  console.log('funArg');
});

The actual parameter related with the “funarg” in this case is the anonymous function passed to the exampleFunc function.

In turn, a function which receives another function as the argument is called a higher-order function (HOF).

Another name of a HOF is a functional or, closer to mathematics — an operator. In the example above, exampleFunc function is a higher-order function.

As it was noted, a function can be not only passed as an argument, but also returned as a value from another function.

A function which returns another function is called a function with a functional value (or a function-valued function).

(function functionValued() {
  return function () {
    console.log('returned function is called');
  };
})()();

Functions which can participate as normal data, i.e. be passed as arguments, receive functional arguments or be returned as functional values, are called first-class functions.

In ECMAScript all functions are first-class.

A function which receives itself as an argument, is called an auto-applicative (or self-applicative) function:

(function selfApplicative(funArg) {

  if (funArg && funArg === selfApplicative) {
    console.log('self-applicative');
    return;
  }

  selfApplicative(selfApplicative);

})();

A function which returns itself is called an auto-replicative (or self-replicative) function. Sometimes, the name self-reproducing is used in a literature:

(function selfReplicative() {
  return selfReplicative;
})();
One of interesting patterns of self-replicative functions is a declarative form of working with a single argument of a collection instead of accepting the collection itself:

// imperative function
// which accepts collection

function registerModes(modes) {
  modes.forEach(registerMode, modes);
}

// usage
registerModes(['roster', 'accounts', 'groups']);

// declarative form using
// self-replicating function

function modes(mode) {
  registerMode(mode); // register one mode
  return modes; // and return the function itself
}

// usage: we just *declare* modes

modes
  ('roster')
  ('accounts')
  ('groups')

However, in practice working with the collection itself can be more efficient and intuitive.

Local variables which are defined in the passed functional argument are of course accessible at activation of this function, since the variable object (environment) which stores the data of the context is created every time on entering the context:

function testFn(funArg) {

  // activation of the funarg, local
  // variable "localVar" is available

  funArg(10); // 20
  funArg(20); // 30

}

testFn(function (arg) {

  let localVar = 10;
  console.log(arg + localVar);

});

However, as we know from the chapter 4, functions in ECMAScript can be enclosed with parent functions and use variables from parent contexts. With this feature so-called a funarg problem is related.

Funarg problem

In stack-oriented programming languages local variables of functions are stored on a stack which is pushed with these variables and function arguments every time when the function is called.

On return from a function the variables are popped from the stack. This model is a big restriction for using functions as functional values (i.e. returning them from parent functions). Mostly this problem appears when a function uses free variables.

A free variable is a variable which is used by a function, but is neither a parameter, nor a local variable of the function.

Example:

function testFn() {

  let localVar = 10;

  function innerFn(innerParam) {
    console.log(innerParam + localVar);
  }

  return innerFn;
}

let someFn = testFn();
someFn(20); // 30

In this example localVar variable is free for the innerFn function.

If this system would use stack-oriented model for storing local variables, it would mean that on return from testFn function all its local variables would be removed from the stack. And this would cause an error at innerFn function activation from the outside.

Moreover, in this particular case, in a stack-oriented implementation, returning of the innerFn function would not be possible at all, since innerFn is also local for testFn and therefore is also removed on returning from the testFn.

Another problem of functional objects is related with passing a function as an argument in a system with dynamic scope implementation.

Example (pseudo-code):

let z = 10;

function foo() {
  console.log(z);
}

foo(); // 10 – with using both static and dynamic scope

(function () {

  let z = 20;
  // NOTE: always 10 in JS!
  foo(); // 10 – with static scope, 20 – with dynamic scope

})();

// the same with passing foo
// as an arguments

(function (funArg) {

  let z = 30;
  funArg(); // 10 – with static scope, 30 – with dynamic scope

})(foo);

We see that in systems with dynamic scope, variable resolution is managed with a dynamic (active) stack of variables. Thus, free variables are searched in the dynamic chain of the current activation — in the place where the function is called, but not in the static (lexical) scope chain which is saved at function creation.

And this can lead to ambiguity. Thus, even if z exists (in contrast with the previous example where local variables would be removed from a stack), there is a question: which value of z (i.e. z from which context, from which scope) should be used in various calls of foo function?

The described cases are two types of the funarg problem — depending on whether we deal with the functional value returned from a function (upward funarg), or with the functional argument passed to the function (downward funarg).

For solving this problem (and its subtypes) the concept of a closure was proposed.

Closure

A closure is a combination of a code block and data of a context in which this code block is created.

Let’s see an example in a pseudo-code:

let x = 20;

function foo() {
  console.log(x); // free variable "x" == 20
}

// Closure for foo
let fooClosure = {
  code: foo // reference to function
  environment: {x: 20}, // context for searching free variables
};

In the example above, fooClosure is a pseudo-code since in ECMAScript foo function already captures the lexical environment of the context where it is created.

The word “lexical” is often implicitly assumed and omitted — in this case it focuses attention that a closure saves its parent variables in the lexical place of the source code, that is — where the function is defined. At next activations of the function, free variables are searched in this saved (closured) context, that we can see in examples above where variable z always should be resolved as 10 in ECMAScript.

In definition we used a generalized concept — “the code block”, however usually the term “function” is used. Though, not in all implementations closures are associated only with functions: for example, in Ruby programming language, a closure can be presented as a procedure object, a lambda-expression or a code block.

Regarding implementations, for storing local variables after the context is destroyed, the stack-based implementation does not fit anymore (because it contradicts the definition of stack-based structure). Therefore in this case captured environments are stored in the dynamic memory (on the “heap”, i.e. heap-based implementations), with using a garbage collector (GC). Such systems are less effective by speed than stack-based systems. However, implementations can always do different optimizations, e.g. not to allocated data on the heap, if this data is not closured.

ECMAScript closures implementation

Having discussed the theory, we at last have reached closures directly in ECMAScript. Here we should notice that ECMAScript uses only static (lexical) scope (whereas in some languages, for example in Perl, variables can be declared using both static or dynamic scope).

let x = 10;

function foo() {
  console.log(x);
}

(function (funArg) {

  let x = 20;

  // variable "x" for funArg is saved statically
  // from the (lexical) context, in which it was created
  // therefore:

  funArg(); // 10, but not 20

})(foo);

Technically, the parent environment is saved in the internal [[Scope]] property of a function. So if we completely understand the [[Scope]] and the scope chain topics, which in detail were discussed in the chapter 4, the question on understanding closures in ECMAScript will disappear by itself.

Referencing to algorithm of functions creation, we see that all functions in ECMAScript are closures, since all of them at creation save scope chain of a parent context. The important moment here is that, regardless — whether a function will be activated later or not — the parent scope is already captured in it at creation time:

let x = 10;

function foo() {
  console.log(x);
}

// foo is a closure
foo: <FunctionObject> = {
  [[Call]]: <code block of foo>,
  [[Scope]]: [
    global: {
      x: 10
    }
  ],
  ... // other properties
};

As we mentioned, for optimization purposes, when a function does not use free variables, implementations may not to save a parent scope chain. However, in ECMAScript specification nothing is said about it; therefore, formally (and by the technical algorithm) — all functions save scope chain in the [[Scope]] property at creation moment.

Some implementations allow access to the closured scope directly. For example in Rhino, for the [[Scope]] property of a function, corresponds a non-standard property __parent__ which we discussed in the chapter about variable object:

var global = this;
var x = 10;

var foo = (function () {

  var y = 20;

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

})();

foo(); // 20
console.log(foo.__parent__.y); // 20

foo.__parent__.y = 30;
foo(); // 30

// we can move through the scope chain further to the top
console.log(foo.__parent__.__parent__ === global); // true
console.log(foo.__parent__.__parent__.x); // 10

One [[Scope]] value for “them all”

It is necessary to notice that closured [[Scope]] in ECMAScript is the same object for several inner functions created in this parent context. It means that modifying the closured variable from one closure, affects the variable in another closure.

That is, all inner functions share the same parent environment.

let firstClosure;
let secondClosure;

function foo() {

  let x = 1;

  firstClosure = function () { return ++x; };
  secondClosure = function () { return --x; };

  x = 2; // affection on AO["x"], which is in [[Scope]] of both closures

  console.log(firstClosure()); // 3, via firstClosure.[[Scope]]
}

foo();

console.log(firstClosure()); // 4
console.log(secondClosure()); // 3

There is a widespread mistake related with this feature. Often programmers get unexpected result, when create functions in a loop, trying to associate with every function the loop’s counter variable, expecting that every function will keep its “own” needed value.

var data = [];

for (var k = 0; k < 3; k++) {
  data[k] = function () {
    console.log(k);
  };
}

data[0](); // 3, but not 0
data[1](); // 3, but not 1
data[2](); // 3, but not 2

The previous example explains this behavior — a scope of a context which creates functions is the same for all three functions. Every function refers it through the [[Scope]] property, and the variable k in this parent scope can be easily changed.

Schematically:

activeContext.Scope = [
  ... // higher variable objects
  {data: [...], k: 3} // activation object
];

data[0].[[Scope]] === Scope;
data[1].[[Scope]] === Scope;
data[2].[[Scope]] === Scope;

Accordingly, at the moment of function activations, last assigned value of k variable, i.e. 3 is used.

This relates to the fact that all variables are created before the code execution, i.e. on entering the context. This behavior is also known as “hosting”.

Creation of additional enclosing context may help to solve the issue:

var data = [];

for (var k = 0; k < 3; k++) {
  data[k] = (function _helper(x) {
    return function () {
      console.log(x);
    };
  })(k); // pass "k" value
}

// now it is correct
data[0](); // 0
data[1](); // 1
data[2](); // 2

Let’s see what has happened in this case.

First, the function _helper is created and immediately activated with the argument k.

Then, returned value of the _helper function is also a function, and exactly it is saved to the corresponding element of the data array.

This technique provides the following effect: being activated, the _helper every time creates a new activation object which has argument x, and the value of this argument is the passed value of k variable.

Thus, the [[Scope]] of returned functions is the following:

data[0].[[Scope]] === [
  ... // higher variable objects
  AO of the parent context: {data: [...], k: 3},
  AO of the _helper context: {x: 0}
];

data[1].[[Scope]] === [
  ... // higher variable objects
  AO of the parent context: {data: [...], k: 3},
  AO of the _helper context: {x: 1}
];

data[2].[[Scope]] === [
  ... // higher variable objects
  AO of the parent context: {data: [...], k: 3},
  AO of the _helper context: {x: 2}
];

We see that now the [[Scope]] property of functions have the reference to the needed value — via the x variable which is captured by the additionally created scope.

Notice, that from the returned functions we still may of course reference k variable — with the same correct for all functions value 3.

Often JavaScript closures incompletely reduced only to the showed above pattern — with creation of the additional function to capture the needed value. From the practical perspective, this pattern really is known, however, from the theoretical perspective as we noted, all functions in ECMAScript are closures.

The described pattern is not a unique though. To get the needed value of k variable is also possible, for example, using the following approach:

var data = [];

for (var k = 0; k < 3; k++) {
  (data[k] = function () {
    console.log(arguments.callee.x);
  }).x = k; // save "k" as a property of the function
}

// also everything is correct
data[0](); // 0
data[1](); // 1
data[2](); // 2
Note: ES6 standardized block scope, which is achieved using let, or const keywords in variable declarations. The example above can be rewritten simply as:

let data = [];

for (let k = 0; k < 3; k++) {
  data[k] = function () {
    console.log(k);
  };
}

// Also correct output.
data[0](); // 0
data[1](); // 1
data[2](); // 2

Funarg and return

Another feature is returning from closures. In ECMAScript, a return statement from a closure returns the control flow to a calling context (a caller). In other languages, for example in Ruby, various forms of closures, which process return statement differently, are possible: it may be return to a caller, or in others cases — a full exit from an active context.

ECMAScript standard return behavior:

function getElement() {

  [1, 2, 3].forEach(element => {

    if (element % 2 == 0) {
      // return to "forEach" function,
      // but not return from the getElement
      console.log('found: ' + element); // found: 2
      return element;
    }

  });

  return null;
}

console.log(getElement()); // null, but not 2

Though, in ECMAScript in such case throwing and catching of some special “break”-exception may help:

const $break = {};

function getElement() {

  try {

    [1, 2, 3].forEach(element => {

      if (element % 2 == 0) {
        // "return" from the getElement
        console.log('found: ' + element); // found: 2
        $break.data = element;
        throw $break;
      }

    });

  } catch (e) {
    if (e == $break) {
      return $break.data;
    }
  }

  return null;
}

console.log(getElement()); // 2

Theory versions

As we noted, often developers incompletely understand as closures only inner functions returned from parent context.

Let’s make a note again, that all functions, independently from their type: anonymous, named, function expression or function declaration, because of the scope chain mechanism, are closures.

An exception to this rule can be functions created via Function constructor which [[Scope]] contains only global object.

And to clarify this question, let’s provide two correct versions of closures regarding ECMAScript:

Closures in ECMAScript are:

  • from the theoretical viewpoint: all functions, since all they save at creation variables of a parent context. Even a simple global function, referencing a global variable refers a free variable and therefore, the general scope chain mechanism is used;

  • from the practical viewpoint: those functions are interesting which:
    • continue to exist after their parent context is finished, e.g. inner functions returned from a parent function;
    • use free variables.

Practical usage of closures

In practice closures may create elegant designs, allowing customization of various calculations defined by a “funarg”. An example the sort method of arrays which accepts as an argument the sort-condition function:

[1, 2, 3].sort((a, b) => {
  ... // sort conditions
});

Or, for example, so-called, mapping functionals as the map method of arrays which maps a new array by the condition of the functional argument:

[1, 2, 3].map(element => {
  return element * 2;
}); // [2, 4, 6]

Often it is convenient to implement search functions with using functional arguments defining almost unlimited conditions for search:

someCollection.find(element => {
  return element.someProperty == 'searchCondition';
});

Also, we may note applying functionals as, for example, a forEach method which applies a function to an array of elements:

[1, 2, 3].forEach(element => {
  if (element % 2 != 0) {
    console.log(element);
  }
}); // 1, 3

By the way, methods of function objects apply and call, also originate in applying functionals of functional programming. We already discussed these methods in a note about this value; here, we see them in a role of applying functionals — a function is applied to arguments (to a list of arguments — in apply, and to positioned arguments — in call):

(function (...args) {
  console.log(args);
}).apply(this, [1, 2, 3]);

Another important application of closures are deferred calls:

let a = 10;
setTimeout(() => {
  console.log(a); // 10, after one second
}, 1000);

And also callback functions:

...
let x = 10;
// only for example
xmlHttpRequestObject.onreadystatechange = function () {
  // callback, which will be called deferral ,
  // when data will be ready;
  // variable "x" here is available,
  // regardless that context in which,
  // it was created already finished
  console.log(x); // 10
};
..

Or e.g. creation of an encapsulated module scope in order to hide implementation details:

// initialization
const M = (function () {

  // Private data.
  let x = 10;
  
  // API.
  return {
    getX() {
      return x;
    },
  };
})();

console.log(M.getX()); // get closured "x" – 10

Conclusion

In this article we tried to discuss closures more from a general theory perspective, i.e. the “Funarg problem”, which I hope made understanding closures in ECMAScript simpler. If you have any questions, as usually I’ll be glad to answer them with in comments.

Additional literature


Translated by: Dmitry Soshnikov.
Published on: 2010-02-28

Originally written by: Dmitry Soshnikov [ru, read »]
Originally published on: 2009-07-20 [ru]

Write a Comment

Comment

60 Comments

  1. The best explanation I have ever read.

  2. Excellent article. I have some suggestions and some questions.
    What do you mean with “lexical context”, perhaps execution context? As you know, environment which implement ECMA 262 standard, edition 3. There, during evaluations of FunctionDeclaraion and FunctionExpression will be created objects. Their [[Scope]] properties, refer object, which is in on the front of Scope Chain. You can give some example with Function Expressions or Function Statements if environment implement. I prefer to use FE:

    with({prop : true}) 
    {
      this.exampleFunc = function() {
        return prop;
      }
    }
    window.alert(this.exampleFunc());  //true
    

    Created function during evaluation of Assignment Expression, refer object which `with` statement put on the front of Scope Chain. There are other examples with `catch` statement, which show same case.

    Another suggestions are about `Function’ constructor. That is only case, which doesn’t form closure. Created object from `Function’ constructor refer Global Object from [[Scope]] property. It is independent by calling execution context and state of Scope Chain during invocation of `Function’ constructor.

    Rhino implementation permit you to make practical example, which show how identifiers resolve against Scope Chain. This can improve understand of readers.

    And last, i suggest you to make shorts introductions. You can concentrate over ES implementations. Of course your introduction here is very good. But, perhaps reader know that. You can put this useful information in additional section and if reader want, he read it and understand why you put there.

    Regards. Excellent article ;~)

  3. @joseanpg, @John Merge

    thanks, colleagues.

    @Asen Bozhilov

    What do you mean with “lexical context”, perhaps execution context?

    No, Asen, as I mentioned, this article is mostly about the general theory than exactly ECMA-262-3 specification. And term “lexical context” relates to this general theory. In ECMA-262-3 for this term stands activation/variable object and scope chain in a whole. Regarding ECMA-262-5, the lexical environment corresponds for this term.

    And about execution context I have separate Chapter 1. Execution context. But this is another topic.

    There, during evaluations of FunctionDeclaraion and FunctionExpression will be created objects. Their [[Scope]] properties, refer object, which is in on the front of Scope Chain. You can give some example with Function Expressions or Function Statements if environment implement.

    Yeah, this is a good example, however, again, the technical part as I told relates to Chapter 4. Scope chain where this mechanism was discussed in detail.

    In this article I tried to concentrate on the general theory explaining the reasons of closures, because even in Richard’s article there’s only description of how it works and exactly in ES (for what I have separate detailed chapter 4), but not about what is it in the theory, and what are the reasons of closures?

    Another suggestions are about `Function’ constructor. That is only case, which doesn’t form closure. Created object from `Function’ constructor refer Global Object from [[Scope]] property. It is independent by calling execution context and state of Scope Chain during invocation of `Function’ constructor.

    I mention this in section Versions of the theory of this article. However, even functions created via Function constructor are partly closures also. That exactly what I was trying to say, when told about that all functions in ECMAScript (regardless their types) are closures.

    var x = 10;
    var f = Function('alert(x);');
    
    (function () {
      var x = 20;
      f(); // 10
    })();

    As you see, “x” name is closured statically (lexically) and this is exactly static (lexical) scope which forms a closure and which is used in ECMAScript.

    And about that [[Scope]] of such functions contains only global object – that’s already another question. But from the theoretical viewpoint — all functions in ECMAScript are closures, but not only which shown in some articles with returning inner functions from outer.

    And last, i suggest you to make shorts introductions. You can concentrate over ES implementations. Of course your introduction here is very good. But, perhaps reader know that. You can put this useful information in additional section and if reader want, he read it and understand why you put there.

    Yeah, maybe, I’ll think about it 😉

    Dmitry.

  4. Very scientific and the best explanation of closures, thank you.

  5. I think that there is a typo at the last line of the last example:
    alert(foo.getA()); // get closured “x” – 10

    It probably need to be like this:
    alert(foo.getX()); // get closured “x” – 10

    I guess that if I’m wrong here I should read again the entire articles up to this point… (actually I plan to do that anyway :))

  6. @Yonatan

    It probably need to be like this:
    alert(foo.getX()); // get closured “x” – 10

    Yep, sure, it was a typo. Thanks, fixed.

    I should read again the entire articles up to this point… (actually I plan to do that anyway :))

    Well, yeah, theoretical article isn’t just a superficial stuff with funny pictures and simplified terminology. The goal of this series is in accuracy of the information and deep theoretical analysis. So, it’s normal to read it twice 😉

    Of course, if will be needed, it is possible to clarify some aspects in comments.

    Dmitry.

  7. hi,Dmitry.

    for example, in Ruby programming language, as a closure a procedure object, a lambda-expression or a code block can be used

    I didn’t understand completely this sentence.Can you give me a detailed explanation? thank you!

  8. @denisdeng

    for example, in Ruby programming language, as a closure a procedure object, a lambda-expression or a code block can be used

    I didn’t understand completely this sentence.Can you give me a detailed explanation? thank you!

    There I just explain that in Ruby there are several ways to create a closure — to show, that a closure isn’t required to be exactly a function:

    a = 10
    
    def foo(&code_block)
      a = 20
      code_block.call # 10 (statically closured), but not 20
    end
    
    # lambda - is a closure
    closure = lambda { print(a) }
    foo(&closure) # 10
    
    # Proc.new - is also a closure
    also_closure = Proc.new { print(a) }
    foo(&also_closure) # 10
    
    # simple code block - {} or do/end
    # is also a closure
    foo { print(a) } # 10

    Every of described approaches has its own features — e.g. some created callable object checks quantity of passed parameters, some — does not, or differently handles return statement. Besides there are other ways to create a closure in Ruby, e.g. to use method function applied for some method — you can find details in documentation for Ruby.

    But my the main idea was to show, that a closure concept isn’t requited to be related exactly with a function concept. Although, in ECMAScript it is so.

    Dmitry.

  9. Hi Dmitry.

    Therefore, in this case as a rule, a closured lexical context is stored in the dynamic memory allocation (“heap”, so-called heap-based implementations), with using the garbage collector (GC) and references counting.

    “a closured lexical context” is the execution context?

    (function(){
        var a=0;
        var b=1;
        var c=2;
        ....
    
        function test(){ alert(a) }
        return test;
    })()

    i use the program above to avoid the variables conflict.

    when the anonymous function finish,the variable a still can be accessed.
    this is because the global object refers the test function,
    and the test function refers the anonymous function’s execution context so the anonymous function’s execution context wont’t be GC.

    if i am wrong,can you explain for me? thanks

  10. @gniavaj

    “a closured lexical context” is the execution context?

    Nope, a “closured context” here means a term mostly from the general theory. Regarding ECMAScript it means a “parent variable object” and, more closer, a complete “parent scope chain”. I think I should correct terminology used in this article to better conform ES terminology.

    if i am wrong,can you explain for me? thanks

    You are correct. However, it’s not a whole context (scope chain, variable object, this value) is saved, but only context’s scope chain (as you know a this value in contrast with other languages, e.g. Ruby or Python, isn’t captured into the closure).

    Dmitry.

  11. thanks for your reply.
    I still have a little confusion.
    the closure we can think it is a structure.
    it contains the function and the context’s scope chain.
    if a function like this

    function a(){
        var b='';
        alert(b);
    }

    we can say the function a create a “a closure”,but running the a function
    dosen’t use the closure technology.

    * exist even if context in which they were created is already finished (e.g. are the functional values returned from function);
    * reference in a code to free variables.

    if one code which meets one of the condition above,we can say the code use the closure technology.

    but if i am correct,in your articel

    Practical usage of closures

    [1, 2, 3].sort(function (a, b) {
      ... // sort conditions
    });

    dose this code use the closure technology?

  12. @gniavaj

    we can say the function a create a “a closure”,but running the a function
    dosen’t use the closure technology.

    You used a practical definition of closures. However, as it was mentioned, theoretically in ECMAScript all functions are closures. Because for all functions at their creation a parent scope chain is saved (this saved scope chain is stored in the [[Scope]] property of functions). I.e. a function possibly won’t be even activated, but the [[Scope]] is already saved at creation.

    A normal global function if uses some global variable is also a closure (though, it’s not so obvious until we won’t have an ambiguous case):

    var foo = 10;
    
    function bar() {
      console.log(foo);
    }
    
    bar(); // 10

    Interesting? Not so (because it’s just an access to the global variable). However, if we pass the same “bar” function as a “funarg”, we see the closure nature (i.e. statically saved parent scope chain — in which “bar” is created, but not when it’s executed):

    var foo = 10;
    
    function bar() {
      console.log(foo);
    }
    
    function baz(funArg) {
      // local "foo"
      var foo = 20;
      funArg(); // 10 (closured), but not 20
    }
    
    baz(bar); // 10

    If a function doesn’t use free variables (as in your example with “a” function), there may be a case with e.g. third-level inner function which does use free variables.

    (function foo() {
    
      // a variable of the
      // "foo" function context
      var x = 10;
    
      // function "bar" does not
      // use free variables. Should it
      // save parent (i.e. "foo"'s) scope
      // chain and be a closure?
      
      (function bar() {
      
        // however, "bar" has another inner
        // function "baz" which uses "x" of "foo"
    
        (function baz() {
          console.log(x); // 10
        })();  
    
      })();
      
    })();

    And since a [[Scope]] is saved at creation, “bar” should save scope chain of “foo” anyway. Because when “baz” is created (at “bar” activation), it takes scope chain of the context in which it is created. And it’s created in the “bar”. More exactly this case may be seen, if first to return “bar” to the outside, when context of “foo” will be already destroyed.

    However, in real practice, if there is some completely safe case (as again with your “a” function), I think implementations may do some optimization and do not save parent’s scope chain and to used even stack but not “heap” (as I wrote in the article). But, it’s already an implementation level and is not described in the ECMA-262. Also more complex parsing rules are needed.

    dose this code use the closure technology?

    Possibly I used not so good example. However, yes, it’s may be (even in practice) also a closure (in theory, repeat, it is a closure anyway). For example (abstractly, not regarding particular implementation in ECMAScript), sort method may be deffered, i.e. activated after some time delay. Thus, if a sort-funarg uses some free variable from parent context, it should be a closure. Or, e.g. a sort-funarg simply may be passed as other function with also free variables:

    var someFreeVariable = true;
    
    function sortFn(a, b) {
      if (someFreeVariable) {
        return a < b ? 0 : 1;
      }
      return -1;
    }
    
    (function foo() {
    
      // another variable with
      // the same name
      var someFreeVariable = false;
    
      // however, sort uses "sortFn"
      // with "someFreeVariable" == true
      return [1, 2, 3].sort(sortFn);
    
    })();

    Dmitry.

  13. Hi, Dmitry. I’m really admire what you do. ECMA should have given you the share of the money for doing their work.

    Anyways, I have a question. In all your articles you mention that the [[Scope]] variable is saved and does not change after creation. So, at what stage the creation of the function is performed. Code parsing?

    Thanks.

  14. @Kostya, thanks (I’ll pass your wishes to ECMA ;))!

    So, at what stage the creation of the function is performed. Code parsing?

    As mentioned in ES3.Ch5, functions are divided into function declarations (FD) and function expressions (FE). The time when each of a function type is created differs, but still, it’s not parsing stage.

    At parsing stage only the parsing itself is applied, that is — ES concrete syntax is transformed into the abstract syntax tree (AST). At this stage, the parser already determined that it has functions in some positions (and even their types, FD, FE). But runtime is not activated at this stage yet.

    And only after that, when the code is executed, then already the interpretation of the parsed AST is started. Here already we enter different execution contexts. And exactly on entering the context stage (but before its actual code execution) the interpreter creates all FDs. And only when it starts to execute the code (the second stage of context handling) all FEs are created.

    So the answer is — no, not at parsing stage, but at runtime context handling stage, which is divided on two stages as well: the entering (FDs are created) and execution (FEs are created).

  15. Dmitry,
    Thanks a lot for your series of articles.
    Firstly, I suppose you have a type in the second code example in this comment.
    Second function declaration is baz?
    Secondly, in general it’s possible to say that closure and Scope = AO + [[Scope]] are the same. Am I correct?

  16. @Sergey

    A closured parent lexical environment is technically only the [[Scope]]. And AO + [[Scope]] is already the complete execution environment (thus, AO is create every time a function is activated).

  17. excellent~~
    more clearly as reading……thks

  18. hi, Dmitry, i’ve read your ECMA-262-3 series of articles (from chapter 1 to 6), thanks for your nice and detailed explanation, however, i still have a question:

    function foo (arg) {
      var x = 10;
      function bar(){}
    
      var someFunc = function(){};//when this statement is executed,
      //it creates a function Object which is assigned to variable someFunc
      //someFunc is stored in AO, and AO is part of active context, thus stored in the stack,
      //but where does the newly created funtion Object stored ? the heap ?
    }
    foo();
    
  19. @allbutone, yes, absolutely correct, the function itself is stored on the heap. And if it’s returned outside and assigned to outer variable, we still have a reference to this object on the heap using this outer var, therefore it’s not removed from heap.

    Moreover, if that inner function uses some parent variables, they also stay live (closured). In the simplest way, the whole AO can be saved on the heap and just referenced from the function (usually via [[Scope]] property). On practice though implementations make optimizations and closure only needed vars.

  20. Thanks in advance

        function testFn(funArg){
            funArg(10); // 20
            funArg(20); // 30
            }
    
        testFn(function (arg){
            var localVar = 10;
            alert(arg + localVar);
        });
    
        // from chapter 2 Variable Object:
        // "on entering the execution context ( but before code execution), VO is filled whit properties ..."
        // from chapter 5 Functions:
        // "FE is created at code execution stage and is not stored in the variable object."
        // from chapter 6 Closures (the example above):
        // "local variable which are defined in the passed functional argument are of course
        // accessible at activation of this function, since the variable object which store the
        // data of the context is created every time on entering the context"
        // Question:
        // it will be more precise to say every time on executing the context?
        // 'cause in this particular case the funArg we activate is a FE.
    
  21. oOk probably I misunderstand your explanation.
    I read your reply @Kostya.
    so FE is created and activated at execution stage of the parent context(i.e testFn) and …“local variable which are defined in the passed functional argument are of course accessible at activation of this function, since the variable object which store the data of the context is created every time on entering the context”
    … it means entering the context of FE itself.
    thank You

  22. Hi Dmirty,

    I am not clear about the second issue of FunArg you mention, could you please give a more detail explanation? why it will lead ambiguity? Thanks.

    And this can lead to ambiguity. Thus, even if z exists (in contrast with the previous example where local variables would be removed from a stack), there is a question: which value of z (i.e. z from which context, from which scope) should be used in various calls of foo function?

    Regards.

  23. @Hong

    This is the case when the function still uses vars from the statically captured scope, rather than from dynamic runtime chain:

    var z = 10;
    
    function foo(funArg) {
      var z = 20;
      funArg(); // 10, but not 20
    }
    
    foo(function() { // downward funarg
      console.log(z);
    });

    You see that z, and there is no ambiguity which z to use: it’s always used from the scope where the function was created, but not where it’s executed.

  24. Hi Dmitry,

    I am still not clear about result of this case.

    Could you please give more detail explanation?

    During case running, I try to analyze the VO, AO, [[Scope]] and Scope as your previous articles, while fail to get your result (seems 20 should be resolved), maybe I still did not understand. Please help.

    ———————

    globalContext.VO === Global = {
      z: 10,
      foo: function
    };
    
    foo.[[Scope]] = [
      globalContext.VO
    ];
    
    fooContext.AO = {
      arguments: funArg,
      z: 20
    };
    
    fooContext.Scope = {
      arguments: funArg,
      z: 20,
      globalContext.VO
    };

    ———————

    In addition, is there any tool to capure those variables during code running, such as capturing those VO, AO, Context, [[Scope]] and Scope variables? Thanks.

    Regards,
    Hong

  25. @Hong, the scopes your descried are correct, but we should analyze the scope and AO of the `funArg` when it’s executed.

    funArg === foo;

    And:

    funArgContext.Scope = funArgContext.AO + funArg.[[Scope]];

    The AO of funArg doesn’t have local vars, and z is found in funArg.[[Scope]], i.e. in the global context. I.e. it’s not affected by the AO of the foo.

  26. @Dmitry, thanks for your explanation :).

    While how can we get the conclustion “funArg === foo”?

    In addition, is there any tool to capure those variables during code running, such as capturing those VO, AO, Context, [[Scope]] and Scope variables? Where do you get this series of concepts, just by analyzing the ECMA specification?

    Thanks, waitting for your comment.

    Regards 🙂

  27. @Hong

    While how can we get the conclustion “funArg === foo”?

    Oh, my typo of course, sorry. What I meant is funArg, that is the anonymous function passed a parameter, has the same [[Scope]] as the foo function (because both functions are created in the global context). Of course funArg is not foo 🙂

    In addition, is there any tool to capure those variables during code running

    Yes, you can use any debugger, e.g. Firebug, or the standard debugger of Chrome. It can show VO, and outer scopes (usually referred as “closure” in the debugger). E.g. https://developer.chrome.com/devtools/docs/javascript-debugging. And the specification of course is the main source of information.

  28. @Dmitry, thanks for your explanation, I got it.

  29. @Dmitry, I am a little confused again. Please help.

    Are following two Forms same to each other?

    Form 1 is easier to understand.
    What I am not clear is that in Form 2, why anaymous funArg of foo has the same [[Scope]] as foo? you mentioned this funArg is also created in the global context, why? it is the argument of foo.

    Form 1

       var z = 10;
    
        function bar () { // downward funarg
          console.log(z);
        }
    
        function foo(funArg) {
          var z = 20;
          funArg(); // 10, but not 20
        }
        
        foo(bar); // downward funarg

    Form 2

       var z = 10;
        
       function foo(funArg) {
         var z = 20;
         funArg(); // 10, but not 20
       }
        
       foo(function() { // downward funarg
         console.log(z);
       });
    

    Waiting your comment.

    Regards.

  30. @Hong

    why anaymous funArg of foo has the same [[Scope]] as foo? you mentioned this funArg is also created in the global context, why? it is the argument of foo.

    Because the actual anonymous function (in line 8) is created in the same context (global context) as the foo function. And then funArg parameter of the foo just receives its value.

    P.S.: Please use at formating [js][/js] for code (no lines are needed, they are inserted automatically), <blockquote></blockquote> for block quotes, and <code><code> for inline code.

  31. @Dmitry

    Sorry for the inconvenient. Thanks for your explanation.

    Because the actual anonymous function (in line 8) is created in the same context (global context) as the foo function. And then funArg parameter of the foo just receives its value.

    Actually, I am just not clear about the reason why the actual anonymous function (in line 8) is created in the same context (global context) as the foo function? we see actual anonymous function is the argument of foo function, why it is also created in the global context?

    Any article mention this point that I have missed?

    Regards.

  32. @Hong

    we see actual anonymous function is the argument of foo function, why it is also created in the global context?

    It is how the parameters are passed in JS. The caller (i.e. the one who calls the function) is responsible for evaluating param values, and the callee (who is called, the foo function in this case) just receives these values.

    So going from top to bottom (and being in the global context), we:

    1. create z
    2. create foo function
    3. create also the anonymous function
    4. and then call foo passing that created anonymous function as a parameter.

    It’s the same as:

    var bar = function() {};
    foo(bar);
    

    Now you see that bar is also created in the global context. But you can omit the temp var and directly create it:

    foo(function() {});

    Then when foo (the callee) is activated, it binding its local funArg parameter to the passed anonymous function. I.e. it doesn’t create it, it just receive it. It was created by the caller (the global context) and just passed to the callee.

  33. @Dmitry, thanks very much for sharing your knowledge.

    It is how the parameters are passed in JS. The caller (i.e. the one who calls the function) is responsible for evaluating param values, and the callee (who is called, the foo function in this case) just receives these values.

    while where you get this? It seems I cannot get them from your series of articles about ECMA-262-3. Or, I miss any section?

    Regards.

  34. @Dmitry

    Reread your article again.

    Another question need your help.

    For the last given case just above Closure section.

    var z = 10;
     
    function foo() {
      alert(z);
    }
     
    foo(); // 10 – with using both static and dynamic scope
     
    (function () {
     
      var z = 20;
      foo(); // 10 – with static scope, 20 – with dynamic scope
     
    })();
     
    // the same with passing foo
    // as an arguments
     
    (function (funArg) {
     
      var z = 30;
      funArg(); // 10 – with static scope, 30 – with dynamic scope
     
    })(foo);

    I think we can consider the last anonymous imediately executed function call (with funArg) as the compressed form of following one, right?

    var ftemp = function (funArg) {
     
      var z = 30;
      funArg(); // 10 – with static scope, 30 – with dynamic scope
     
    };
    
    ftemp(foo);

    So this anonymous function is created in global context, and we can get VO and Scope of anonymous function context.

    anonymousfunContext.VO = {
      globalContext.VO
    };
    
    anonymousfunContext.Scope = {
      arguments: ,
      z: 30,
      globalContext.VO
    };

    while VO and Scope do not affect the final resolution of z, which will be resolved by foo.[[Scope]] (created at the creation of foo).

  35. @Hong yeah, that’s correct, when `foo` is called inside (via the `funArg` name), all variables are searched in the `fooContext.AO` (for local vars) and `foo.[[scope]]` (for free vars).

  36. Hi Dmitry, very well explained.
    In ES6 we get block scope, that means that each block will have some kind of VO/AO where block-bindings are stored ? Can I think of it in that way ? Thank you.

  37. @blajs, yes, correct, a new environment is created for let. Although, it’s more optimized than AO, since it doesn’t need to store some data (like arguments), that functions have.

  38. Hi,Dmitry,I had a problem which confused me. Could you explain for me why this line136 used IIFE to save a variable. I think ‘a’ name is an object referrence. If you use the variable in anoymouse function, the variable a outside is also modified if the inner function modified the a variable. What does the code mean for?Thanks very much!

  39. @bird, yeah, passing it as a param seems useless, since the a is automatically captured by all closures, and can be accessed (and mutated) without any parameters.

  40. Hi Dmitry ! Great article as usually !

    According to `variable objects` article, after entering phase the example with « hoisting » should be for Scope this:

    activeFunctionContext.Scope = [
       // ....
      { data: [], k: undefined }
    

    but your `k` have already the `3` value. Why ?

    For me, it’s while the execution phase the `undefined` is setted so the note « it’s because that value is resolved during enterring phase » is really true ? Or in `object variables` article the example is false ?

    AO(test) = {
      a: 10,
      b: undefined,
      c: undefined,
      d: 
      e: undefined,
      k: undefined // and not `3` for example
    };
    

    I think it’s durring execution phase the `k` value is effectively resolved but because this value is affeted at the same line of code, each output have the latest value ?

    No ?

  41. @Bruno Lesieur, good point! And you are correct, the value of k is undefined on entering the context stage, and it’s changed to 3 only at execution stage. In this case I just simplified, and skipped the first stage, noting that eventually k will be 3.

  42. Hi Dmitry! Great article!!! I have a question: ES6 standardized block scope, so where does the block variable store? like let a = 10, where variable ‘a’ store? It should not store in VO obvious.

  43. @Joiner, since ES5 (and in ES6) VO/AO are combined under one abstraction, called environment. See — this chapter — to understand environments in JS.

    The let bindings are normally stored in the environment, and a new environment is created for a block if let variables are used inside (so they are added to the block environment; on exit from block the environment is destroyed, unless is captured by a closure).

    In global context, the global environment also contains let bindings, but in contrast with var bindings do not add let-variables to the binding object (which is this value in the global context), so it’s not possible to access let-variables as properties of the global object:

    
    // Added to the environment, AND to
    // the binding object, i.e. `this`:
    var x = 10;
    
    console.log(
      x, // 10 - from the environment record
      this.x // 10 - from the binding object
    );
    
    // Added to the environment, but not to
    // the binding object:
    let y = 20;
    
    console.log(
      y, // 20 - from the environment record
      this.y // undefined - not added to the binding object
    );
    
    // Entering the block, a new environment is created:
    {
      let z = 30;
    
      console.log(z); // 30 - from the block environment
    }
    
    // On block exit, its environment is destroyed
    
    console.log(z); // ReferenceError, "z" is not defined
    
    
  44. thanks, after read the environments article and have a question about ‘object environment record’.
    Is there also a binding object in the object environment record? The relationship between global object and object environment record of the global context environments?