0

If we assume we shadow all the variable from global scope. is a closure still created?

function init() {  
  function displayName() { 
    // if all variables from global are re-declared here
    alert("no free variables"); 
  }
  displayName();
}
init();

I have read this one, How do JavaScript closures work?

The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
  • 2
    Yes, or maybe "yes and no". *Every* function call creates a dynamic invocation scope, but in the example the closure doesn't "leak" from the function, so it's a "tree falling in the forest" scenario. The closure is created but no information about it makes it out of `init()`. – Pointy May 05 '20 at 02:04
  • Also the shadowing of relatively-global symbols doesn't have a lot to do with what a closure is. – Pointy May 05 '20 at 02:07
  • @Pointy closure is a function bundled together with its lexical environment, right? in this particular example, the closure is not having free variables, i used showing to avoid that free variables so that closure will not have free variables. – The Scientific Method May 05 '20 at 02:10
  • The point of my comment was that because neither `init()` nor `displayName()` return a value or (as far as I can tell) modify relatively-global variables, whether there's a closure created or not is basically indeterminate; there's no way to tell from JavaScript code. It's *possible* that a runtime would set things up for a persistent (to whatever extent) closure, but it kind-of doesn't matter one way or the other. – Pointy May 05 '20 at 02:14
  • 1
    And no, that's not really exactly what a closure is. It's the *dynamic* environment that captures current values from the lexical context when a function is invoked. – Pointy May 05 '20 at 02:15
  • Your example probably should actually re-declare the `alert` variable, not just have a comment about it. – Bergi May 05 '20 at 16:52

0 Answers0