0

I'm pretty new to JS and the whole idea of closures. Here's a trivial example of some code that makes use of closures.

window.onclick = function() {
    const x = "WOOHOO!";
    (function myFunc() {
      console.log(x);
    })();
  }

Here, the inner IIFE has access to the x variable because of closures. However, I'm not entirely sure why the following does not work the same way, and requires the passing of a variable.

  window.onclick = function() {
    const x = "WOOHOO!";
    myFunc();
  }

  function myFunc() {
    console.log(x);
  }

This does not work. You have to do

  window.onclick = function() {
    const x = "WOOHOO!";
    myFunc(x);
  }

  function myFunc(val) {
    console.log(val);
  }

Can someone provide a simple but somewhat detailed explanation of why the second example does not work and requires the passing of an argument?

  • Because of the [scoping of variables](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – empiric Jan 13 '21 at 07:54
  • @empiric To my untrained eye, it's still not obvious why this doesn't work. Does the scope of variables resolve in the function declaration before it is invoked? – embracethefuture Jan 13 '21 at 07:55
  • From Closures [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures), 1. *A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)* So `x` should be in the lexical scope, what you referring in your second example is not lexical scope, it's kinda dynamic scope. 2. *In JavaScript, closures are created every time a function is created, at function creation time.*. So calling `myFunc` does does not count as a function creation. – c0m1t Jan 13 '21 at 07:55
  • Here is a link to read more about [lexiacal scope](https://stackoverflow.com/a/1047491/5289334) – c0m1t Jan 13 '21 at 07:57
  • Not sure if closing this question as a duplicate, gave you the answer so: On the first example you `x` is in the scope of `myFunc`. On the second example its not. You can't just declare a variable anywhere and expect it to be globally accessible (in function or not). Scope is not determined at the invocation time. It's determined at the declaration time. – Tarmo Jan 13 '21 at 07:58

0 Answers0