4

I was trying out a very basic example of Javascript closure, but I am not able to visualize it in Chrome devtools. Please see the screenshot.

I have created a global variable

var p = 3;

and a function

function f1() {
    var q = 2; 
    return p+q;
}

This function is using the global variable p inside it, so this is a closure, right? Please guide me if my understanding is not correct.

So, if this is a closure then why doesn't it shown in the function scope as "Closure"?

enter image description here

JJJ
  • 32,902
  • 20
  • 89
  • 102
Roy
  • 503
  • 2
  • 8
  • 20
  • 1
    Technically speaking, referring to a global variable does not constitute a closure. A closure is when a function closes over a variable in an enclosing **function** scope. (You may find people who claim that closing over a global variable constitutes a closure, but actually that is not the case--and the Chrome devtools display you see reflects that.) For more on this topic, see http://stackoverflow.com/questions/35130415/is-every-function-a-closure/35131645#35131645. –  Feb 13 '16 at 10:27
  • @torazaburo... in the book JavaScript- The Definitive Guide, By David Flanagan it is mentioned .."Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them."... In this case as well it has scope chain associated right ? – Roy Feb 13 '16 at 10:38
  • 4
    Well, if you prefer to look at it that way, the devtools display **is** showing the closure; it just happens to call it "Global" in this case, since it's the global scope. However, as the question I linked to above discusses, it's somewhere between unhelpful and confusing to refer to this particular case as a closure. What the book says is not wrong in the narrow sense, but the key word is "technically". Calling this case a closure is inconsistent with how the word is commonly used, and it's inconsistent with the way engines actually implement it. –  Feb 13 '16 at 11:08
  • @torazaburo...+1 I saw the discussion link, its helpful... yes I agree that calling this particular case a closure does not make much sense... – Roy Feb 13 '16 at 12:38
  • See also [here](http://stackoverflow.com/q/30252621/1048572) – Bergi Feb 13 '16 at 12:44

1 Answers1

5

w3schools.com says "A closure is a function having access to the parent scope, even after the parent function has closed." In your example, p is defined in the global scope, not a parent function. If you wrap your code in a parent function, in the dev tools, you will see p listed under closure.

var f2  = function(){

    var p = 3;

    var f1 = function(){
        var q = 2;
        return p + q;
    }

    return f1;

}();

console.dir(f2);

enter image description here

Ben Nieting
  • 1,360
  • 2
  • 14
  • 23