Lexical scoping and closures are related concepts in programming, but they are not the same thing. Here's a brief explanation of each:
Lexical scoping: refers to the way a programming language determines how variables are scoped (i.e., how they are accessible or not) based on their position in the code. In a lexically-scoped language like JavaScript, a variable declared inside a function is only accessible within that function and any nested functions within it. The outer scope, such as the global scope, cannot access those variables.
function outer() { let x = 10; function inner() { console.log(x); } inner(); } outer(); // Output: 10
In this example, we have a function
outer
that declares a variablex
and a nested functioninner
that logs the value ofx
to the console. When we callouter
, it callsinner
, which is able to access the variablex
because of lexical scoping. Sincex
is declared in the outer function, it is accessible to the inner function and can be logged into the console.Closures: A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure "closes over" the variables it needs from its outer scope and maintains a reference to them, even if those variables would otherwise be inaccessible. This can be useful for creating private variables or for preserving state across function calls.
function outer() { let x = 10; function inner() { console.log(x); } return inner; } let closureFunc = outer(); closureFunc(); // Output: 10
In this example, we have the same
outer
andinner
functions as before, but this time we're returning theinner
function fromouter
and assigning it to a variableclosureFunc
. When we callclosureFunc
, it logs the value ofx
to the console, just like before. However, the difference here is thatinner
has access to the variablex
even afterouter
has finished executing, Thanks to the concept of closures. In other words,inner
"closes over" the variablex
and maintains a reference to it, even thoughouter
has finished executing.
Closures are possible in languages with lexical scoping, but not all languages with lexical scoping have closures. In JavaScript, for example, closures are commonly used to create private variables and functions, and to preserve state in asynchronous code.