DEV Community

Ramya Sri M
Ramya Sri M

Posted on

2 1 1 1 1

Closures in JS🤯

Closures🔥

  • A function, bundled together with its lexical scope, forms a closure.
  • A closure provides access to an outer function's scope from an inner function.
function x() {
   var a = 7;
   function y() {
       console.log(a) ;
   }
  y() ;
}
x() ;  
// 7
Enter fullscreen mode Exit fullscreen mode

In this program, when y() tries to run, it looks for 'a' in its local memory. Since it does not find it there, it accesses its lexical parent, x.

function x() {
   var a = 7;
   function y() {
       console.log(a) ;
   }
  return  y;
}
var z = x() ;
console.log(z) ; //Ć’ y() {console.log(a); }
z() ; // 7
Enter fullscreen mode Exit fullscreen mode

In the above program, the console.log statement returns the function y() (i.e., function y() { console.log(a); }). When 'y' is returned, the function is returned, and the entire closure (the function y along with its lexical scope) is returned and assigned to 'z'. As a result, when 'z' is used elsewhere in the program, it still retains access to the variable 'a' inside x(). Even though x() no longer exists, the 'y' function remembers its lexical scope, allowing z() to output 7.

Whenever a function is returned, even if it vanishes from the execution context, it still retains the reference it was pointing to. It does not return just the function alone but the entire closure.

function z() {
    var b = 100;
    function x() {
        var a=7;
        function y(){
            console.log(a,b);
        }
        y();
    }
    x();
}
z(); 
Enter fullscreen mode Exit fullscreen mode

Closures

In the above image, 'y' forms a closure with the scope of 'x' and the scope of 'z'.

Credits to Akshay Saini. [(https://youtu.be/qikxEIxsXco?si=sRe_4k5swSbnr50T)]

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (2)

Collapse
 
abhivyaktii profile image
Abhinav •

Intersting read.

Collapse
 
ramya_srim profile image
Ramya Sri M •

Thank You.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay