2

Since closure is a function binded to it's lexical environment I wonder why notAClosure construction is not a closure:

let a = { b: 42 };
let notAClosure = ( param ) => { param.b++ };
let aClosure = () => { a.b++ };
notAClosure(a);

When notAClosure called, we pass to it object a by reference. This means that now inside closure we have access to outer scope = lexical environment. Did I name functions right? Is aClosure a real closure? Is notAClosure really not a closure and if is is correct - then why?

zelibobla
  • 1,498
  • 1
  • 16
  • 23
  • 2
    A function only forms a closure if it's accessing variables that are defined in the outer scope. `param` is a local variable, so `notAClosure` isn't a closure. All functions have access to global variables, so `aClosure` isn't really a closure if `a` is global. – 4castle Aug 08 '17 at 18:56
  • 1
    Why does this matter to you? Is there a real-world scenario where there is a difference in your code? This seems purely philosophical. – Graham Aug 08 '17 at 18:56

2 Answers2

1

Your variable naming is correct.

The function body of notAClosure does not actually refer to anything outside of its own scope. The function aClosure does refer to a variable outside of its own scope, which is a.

a is passed to notAClosure by-value-by-reference. This places a "value" reference to a within the immediate scope of notAClosure's function body, as param is an argument.

Within aClosure, there is no a in the local scope; instead, the function is (forced to) refer to the a in the outer scope. A slightly more complex example, to make it more obvious why it becomes a closure:

let x = (function() {
    let a = { b: 42 };
    return () => { a.b++; };
})();

x is assigned to a function which immediately returns another function. x "hides" a in the closure of the returned lambda function. It is impossible to access a in any way without calling x, but a still exists in memory because it is accessible within the outer scope, and thus the scope, of the returned lambda.

heartyporridge
  • 1,151
  • 8
  • 25
0

your function aClosure is simply accessing to your a variable through global scope, hence, it's not a closure, you can see it actually modifies a.b value in this example:

let a = { b: 42 };
let aClosure = () => { a.b++ };

console.log(a.b);   //42
aClosure();
console.log(a.b);   //43 

if you want to understand closures better I'd recommend this book.

  • Could you please refer to any closure definition that contains a 'global' term? If no, then what is the role of globality of the outer scope for understanding closures? – zelibobla Aug 09 '17 at 14:12
  • Excuse me if I'm wrong, but a closure happens when a function, callback or the like, have access to its 'own' values. Here I show that because of `aClosure()` modifies the value of a.b in the global scope it is not a closure. – Guy who types fast Aug 09 '17 at 14:39