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.