1

Consider the following code:

function nepaliBuddha() {
    var a = 20;

    return function buddhaNepal() {
        console.log(a); 
    }
}

var closure = nepaliBuddha();

closure(); // logs 20
  1. Now when we invoke closure output is 20. This proves that the internal scope property ([[scope]]) was assigned to the inner function where it was defined or say when declared.If this wasn't assigned at declaration ,there was no way to log 20 as it gets invoked in different context

  2. Invoking closure() the scope chain of a function context is created at function call and consists of the activation object or VO of the current context and the internal [[scope]] property of this function.

  3. Invocation also creates [[scope]] property , this means that internal scope property is created at declaration as well as at execution isn't it?

  4. Usually the definition says the [[scope]] property gets created at run time or at function call but this isn't true as [[scope]] property is already assigned at declaration as well.

  5. What I think is the [[scope]] property might get updated after execution of function, is it? Please give clear definition of [[scope]] internal property. How and when it is created at declaration time or at execution time or at both time.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Maizere Pathak.Nepal
  • 2,383
  • 3
  • 27
  • 41
  • 1
    I don't believe that the closure is created twice. I think by definition it won't be garbage collected until the function that has a reference to it also goes out of scope. If you're asking if a second call to NephaliBuddha would create another scope then yes it would. It would be independent of the one created earlier. – Hath995 Jul 08 '13 at 05:13
  • 1
    possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Paul Jul 08 '13 at 05:25
  • the question linked is realted to closure ,I m asking for internal scope property not about closure – Maizere Pathak.Nepal Jul 08 '13 at 05:47
  • 1
    It isn't very clear exactly what you're asking. There seems to be several possible questions in what you originally wrote. – rossipedia Jul 08 '13 at 05:56
  • 1
    The variable ``a`` is bound to the scope inside ``nepaliBuddha``. But besides that, @Maziere, it seems like you are discussing some internals that doesn't affect how JavaScript is interpreted or executed. In that case, it may be implementation dependent. If you think otherwise, why not provide a test that proves your point? – mzedeler Jul 08 '13 at 05:58
  • Your inner closure is created _on_ and _each time_ you call buddha. Prepend your closure `a++;`, create two variables, call two times buddha and then run these returned closures different times. You'll see that there are two scopes for two buddhas. – metadings Jul 08 '13 at 06:03

2 Answers2

9

Wow, aren't you thoroughly confused. Alright, I'll try to explain closures as simply as possible.

First, we'll start with scopes. There are two types of scopes:

  1. Block scopes
  2. Function scopes

A block scope begins immediately when it occurs in the program. A function scope on the other hand does not begin until the function is called. Hence multiple calls to the same function result in multiple scopes being created.

JavaScript does not have block scopes. It only has function scopes. Hence to emulate a block scope we need to create a function expression and immediately execute it. This patttern is called an immediately invoked function expression (IIFE) and it looks like this:

(function () {
    // this is the JS equivalent of a block scope
}());

Beside block scopes and function scopes there's another way to classify scopes. Hence we also have:

  1. Lexical scopes
  2. Dynamic scopes

This distinction only applies to function scopes because block scopes are always lexically scoped. JavaScript only has lexical scopes.

To understand the difference between lexical scopes and dynamic scopes we need to understand the difference between free and bound variables.

  1. A free variable is a variable which is used within a function but which is not declared within that function.
  2. A variable which is declared within a function is said to be bound to that function.

Consider the following program:

function add(x, y) {
    return x + y; // x and y are bound to add
}

In the above program the variables x and y are bound to the function add because they are declared within add.

On the other hand the variables x and y in the following program are free within the function add because they are not declared within add but they are used within add:

function add() {
    return x + y; // x and y are free within add
}

Now free variables are a problem. They need to be mapped to some value, but which value? This is where lexical and dynamic scopes come into picture. I won't go into the major details, but you can read about it on Wikipedia.

Scopes are a lot like prototypal inheritance. When a new scope begins it inherits from a parent scope forming a chain of scopes much like prototype chains in JavaScript.

Lexical scopes and dynamic scopes differ with respect to which parent scope a new scope inherits form.

  1. In lexical scoping a new function scope inherits from the scope in which that function was defined (i.e. its lexical environment).
  2. In dynamic scoping a new function scope inherits from the scope in which that function was called (i.e. the calling scope).

Since JavaScript only has lexical scoping we won't bother with dynamic scoping. Consider the following program:

var count = 0;

function incrementCount() {
    return ++count;
}

(function () {
    var count = 100;
    alert(incrementCount()); // 1
}());

Here the function incrementCounter has one free variable - count. Since JavaScript has lexical scoping count will be mapped to the global variable count instead of the local count declared within the IIFE. Hence incrementCount returns 1 and not 101.

Now closures only work in languages which have lexical scoping. Consider the following program:

function getCounter() {
    var count = 0;

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

var counter = getCounter();

alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3

In the above program the function returned by getCounter is a closure with respect to the variable count because:

  1. The variable count is free within the returned function (i.e. counter).
  2. The function is moved outside of the scope within which count is declared.

Both these conditions are necessary for a function to be called a closure. For more information read the following answer: https://stackoverflow.com/a/12931785/783743

Now the important thing to understand here is that the function counter will still be called a closure even though it may never be invoked. A closure is simply a function which closes over a variable (which is called the upvalue of the closure).

When we invoke getCounter we create a new scope (let's call this scope A), and each time we invoke the function returned by getCounter (i.e. counter) we create a new scope which inherits from scope A. That's all. No new closure is created.

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • let me ask u one thing,when we declare any function will it be assigned internal scope property immediately?If yes, the internal scope property is also assigned at run time or when u invoke function.My question was two times internal scope property is beign created.So what should i say now to my stds ,when will the internal scope property gets created? – Maizere Pathak.Nepal Jul 08 '13 at 07:08
  • No. When you define a function JavaScript creates an internal property called `[[scope]]` on the function which contains the lexical scope __to which the function belongs__. For example when I create a function in the global scope then the `[[scope]]` property of that function will be set to the global scope. When I invoke a function then JavaScript creates a new scope (activation object) which inherits from whatever the `[[scope]]` property of that function points to. The `[[scope]]` property is not modified when you invoke a function. It's simply used to determine which scope to inherit from – Aadit M Shah Jul 08 '13 at 07:19
  • @Maizere Read the above comment. Now think about it logically. When you invoke a function you're creating a new scope. This scope must inherit from another scope, but which one? We need to store the lexical scope of the function somewhere so that when we invoke the function we can set up the scope chain of the new scope properly. The lexical scope of each function is stored in its internal `[[scope]]` property. It's only set once (at the time the function is created) and never modified. It's read-only. If JavaScript had dynamic scoping then there would be no need for a `[[scope]]` property. =) – Aadit M Shah Jul 08 '13 at 07:24
1

A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.

function makeFunc() {
    var name = "Mozilla";
    function displayName() {
        alert(name);
    }
    return displayName;
}

Now call makeFunc()

var myFunc = makeFunc();
myFunc();

In this case, myFunc is a closure that incorporates both the displayName function and the "Mozilla" string that existed when the closure was created, MDN.

So, the scope created exactly when I called var myFunc = makeFunc(); and myFunc() (the result of the makeFunc() call) is now a closure. So, go to the first line where

A closure is a special kind of object that combines two things: a function, and the environment in which that function was created.

Now consider these

function nepaliBuddha() {
    var a = 1;
    return function buddhaNepal() {
        a = a+1;
        console.log(a);  
    }
}
var closure1 = nepaliBuddha(); // An individual scope
var closure2 = nepaliBuddha(); // An individual scope

closure1(); // 1 
closure1(); // 2

closure2(); // 1
closure2(); // 2
closure2(); // 3

Demo.

Which means, closure1() and closure2() are closures and both have their personal scope/environment and they have access to their own scope once they get it (in this case, every time you call nepaliBuddha you are creating a closure and giving/saving it to a variable).

Scope defines the area, where functions, variables and such are available. So, when you defined/declared the function buddhaNepal (inner function) inside the nepaliBuddha (outer function) the buddhaNepal (inner function) has been just separated from the global scope and nothing else. It can't access anything in the global scope but it has it's own scope, that's it. The nepaliBuddha (outer function) is the boundary of the buddhaNepal (inner function) and in this case the nepaliBuddha outer function's local scope/environment is the global scope for the buddhaNepal (inner function).

in JavaScript, this is known as Lexical Scopeing it defines how variable names are resolved in nested functions. Other names of Lexical Scope are Static Scoping or Closure. It means that the scope of an inner function contains the scope of a parent function.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • There's nothing special about a closure. It's just like any another JavaScript function. However closures are more interesting than other functions because a closure keeps its upvalues alive even after they go out of scope. I used to think that closures were special too and that they were handled differently from other functions. However this is not the case - the JavaScript interpreter handles each function in the same way. For more information read the following comment: http://stackoverflow.com/questions/12930272/javascript-closures-vs-anonymous-functions/12931785#comment17582302_12931785 – Aadit M Shah Jul 08 '13 at 07:45
  • @AaditMShah, Yes, that's exactly the case, the `closure` is just a function but thee live in a different scope. – The Alpha Jul 08 '13 at 07:47