(ES6) ES6 (2016)

Closures (CA01)

   1:  function outerFunction() {
   2:      let outerVar = "I'm outside!";  //Outer variable
   3:      function innerFunction() {
   4:          console.log(outerVar); // Inner function has access to outerVar (closure)
   5:      }
   6:      return innerFunction; // Return inner function from parent function
   7:  }
   8:  const myClosure = outerFunction(); // myClosure holds a reference to innerFunction
   9:  myClosure(); // Output: "I'm outside!" (even though outerFunction has finished executing, innerFunction can access outerVar through closure.)



Basic Closure (Function within a Function):
innerFunction "closes over" outerVar, forming a closure. Even after outerFunction completes, innerFunction retains access to outerVar.
A closure is a function that "remembers" its surrounding state (the lexical environment) even after the outer function has finished executing.
It "closes over" the variables from its outer scope.

I'm outside!





Closures context:






ES6 context:



Comments ( )
Link to this page: http://www.vb-net.com/JavascriptES6/CA01.htm
< THANKS ME>