0
var foo = 'outer';
function outer() {
    var foo = 'closure';
    var bar = 'baz';
    return function inner() {
        console.log(foo);
    }   
}

I understand that foo will be closed over, because inner() will need it.

But will bar be closed over also? It's in inner()'s scope, but it isn't being used by inner().

Adam Zerner
  • 17,797
  • 15
  • 90
  • 156

2 Answers2

1

The particular variable alone will not be carry forwarded. The whole scope will be carry forwarded when a closure is created. In this case foo and bar and whatever variables present in that scope will be available in inner function.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • Ok thanks. So is it just the direct parent scope that's carried forward, or is it all parent scopes? And do other languages implement this differently? It seems excessive to carry the whole scope forward when you only need parts of it. – Adam Zerner Dec 04 '14 at 15:10
  • 1
    @AdamZerner the scope of the variable which you're using in the inner function will be carry forwarded – Amit Joki Dec 04 '14 at 15:11
  • Ah ok. So since `foo` is used in `inner`, and since `foo`'s scope is `outer`, `outer` will be carried forward in `inner`? – Adam Zerner Dec 04 '14 at 15:13
  • yup. You could say so @AdamZerner – Amit Joki Dec 04 '14 at 15:14
  • Actually it seems that "all variables that are in scope at the point of `inner`'s declaration are available in the closure" (paraphrased from Secrets of the JavaScript Ninja – Adam Zerner Dec 04 '14 at 16:49
1

Theoretically, the whole parent scope is closed over, including the variables foo and bar and the reference to its parent scope: the function inner might need it. At least that's how it is specced. In practise, engines are free to optimise this and garbage-collect everything that is not referenced - for example, V8 does this.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Just the parent scope? It seems that "all variables that are in scope at the point of inner's declaration are available in the closure" (paraphrased from Secrets of the JavaScript Ninja – Adam Zerner Dec 04 '14 at 16:50
  • 1
    @AdamZerner: There is a chain of scopes, each one has a reference to its parent scope. A closure scope can (will) be shared amongst all functions defined in it. "*all variables in scope*" refers to the current scope variables, and all other variables accessible from there. – Bergi Dec 04 '14 at 16:54