JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network
Q&A Logo

How does a closure maintain access to variables in its outer scope even after the outer function has returned?

Asked on Oct 01, 2025

Answer

Closures in JavaScript allow a function to access variables from its outer scope even after the outer function has returned. This is achieved because JavaScript functions form closures around the environment in which they were created.
<!-- BEGIN COPY / PASTE -->
        function outerFunction() {
            let outerVariable = "I'm outside!";
            
            function innerFunction() {
                console.log(outerVariable);
            }
            
            return innerFunction;
        }

        const closureExample = outerFunction();
        closureExample(); // Logs: "I'm outside!"
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "outerFunction" creates a local variable "outerVariable".
  • "innerFunction" is defined within "outerFunction" and can access "outerVariable".
  • When "outerFunction" is called, it returns "innerFunction", which maintains access to "outerVariable" even after "outerFunction" has finished executing.
  • This is because the returned "innerFunction" forms a closure, preserving the environment in which it was created.
✅ Answered with JavaScript best practices.
← Back to All Questions