Closures in JS

1 5
calendar_todayschedule1 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)]

2 Comments

0 votes
1
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23

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

Karol Modelskiverified - Apr 9

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

Karol Modelskiverified - Mar 19

The Reality of Roadmaps 🗺️

Ijay - Jun 30

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10
chevron_left
136 Points6 Badges
India
1Posts
1Comments
1Connections
Hi, I'm Ramya Sri. I enjoy learning new things, diving deep into how they work, and sharing that kno... Show more

Related Jobs

View all jobs →

Commenters (This Week)

3 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!