1

I have question about closures in JavaScript. The thing I was wondering is every function that uses variables from outter scope is automatically closure?

Take a look at code example, is it closure?

const x = 2;
function foo() {
    console.log(x);
}

I've also read stackoverflow thread which contains two inconsistent statements. The "no" answer links wikipedia and it states that:

Lastly, a closure is only distinct from a function with free variables when outside of the scope of the non-local variables, otherwise the defining environment and the execution environment coincide and there is nothing to distinguish these (static and dynamic binding cannot be distinguished because the names resolve to the same values).

But there are seemingly valid points coming in the comments from user T.J. Crowder.

This may or may not be true for other languages, but in JavaScript, all functions are closures. It's intrinsic to them, in JavaScript. There is nothing special about closures over other contexts that marks them out as distinct from functions that only close over the global context. See §9.2.5 - FunctionCreate and its uses for details.

They're all closures (in JS) because the mechanism by which global variables works in JavaScript is exactly the same mechanism by which closing over variables from other contexts works. There is no distinction, at all. This "functions with free variables" vs. "closures" semantic distinction may or may not be valid for languages I don't know as well as JavaScript, and as I said in my answer, we don't usually call them closures unless you're using them for their access to something non-global. But that doesn't mean they aren't closures. :-)

Coming back to first code snippet, basically "foo" would have to return function which then console logs? Or still it wouldn't be closure and the "x" variable should have been moved to foo's body?

Like this?

function foo() {
    const x = 2;
    return () => console.log(x);
}

I am confused.

tilon
  • 11
  • 2
  • [Yes, it's a closure](https://stackoverflow.com/q/30252621/1048572) according to the language specification, but it doesn't matter if it's indistinguishable from a non-closure. The "no" answer you've linked is not very convincing. – Bergi Feb 26 '22 at 20:45

1 Answers1

0

I suggest - if you didn't - to check MDN Docs that are really quite exhaustive about Closures (and with lots of examples).

In the very first paragraph of the linked page you can just find an answer to your question:

In JavaScript, closures are created every time a function is created, at function creation time.

cheesyMan
  • 1,494
  • 1
  • 4
  • 13
  • Yea, I read that. This qoute alone states that function in first snippet is closure. I am still not sure about that. – tilon Feb 26 '22 at 20:19