Closures in JS

●2 ●6
calendar_today • schedule1 min read
— Originally published at dev.to

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

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

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(); 

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)]

Want more #programming & #javascript deep dives?

Join 6,134+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

2 Comments

0 votes
1

More Posts

Frameworks Are Institutional Memory

Ken W. Algerverified - Sep 17

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelski - Apr 9

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelski - Mar 19

A Message From Our Founder: On the Winding Down of LaaSy™

Ken W. Algerverified - Oct 29
chevron_left
136 Points • 8 Badges
India
1Posts
1Comments
4Connections
Hi, I'm Ramya Sri. I enjoy learning new things, diving deep into how they work, and sharing that kno... Show more

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!