0

I thought that I understand closures, but this example made me confused.

function f() {
  let x = 1;

  const g = () => {
    console.log(x);
  }
  x = 100;

  g();
}

f()

I think that the result should be 1, but it is 100.

I thought that g in the moment of a declaration should take x that exists in the outer scope.

But it took x value after reassignment.

Why is it working like this?

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Moti
  • 312
  • 3
  • 8
  • *"I thought that `g` in the moment of declaration should take `x` that exists in outer scope."* It does, but not the **value** of `x`, **`x` itself**, the variable. So if you change the value the variable holds, `g` sees the new value. More specifically, `g` has a live reference to the context in which it was created, and that context includes the in-scope variables. See the linked question's answers or my old blog post [*Closures are not complicated*](http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html). – T.J. Crowder Feb 23 '21 at 08:58
  • Expanding on that a bit: When you call `f`, an *execution context* is created which contains a conceptual object (called a *lexical environment*) that holds the names and values of the variables declared in `f`. When you create `g`, it gets a link to that environment object (which is what we mean by "`g` closes over" that environment). When you use `x` within `g`, since `g` doesn't have its own `x` it uses that link to the outer environment to see if `x` exists there. In this case, it does, so it uses the then-current value of `x`. – T.J. Crowder Feb 23 '21 at 09:02
  • It may help to understand that this is exactly the way global variables work. If you took your code in `f` outside of `f` and ran it, `x` would be a global, and `g` would use that global -- because `g` closes over the global lexical environment containing `x`. It's exactly the same mechanism. :-) – T.J. Crowder Feb 23 '21 at 09:04
  • 1
    Oh, I understand now. Thanks. I have some background in Racket, so I thought that it works almost exactly the same. – Moti Feb 23 '21 at 09:05

0 Answers0