DEV Community

Cover image for 🚀Closure in Javascript👨‍💻
Nawaz Mujawar
Nawaz Mujawar

Posted on

3 2

🚀Closure in Javascript👨‍💻

Hello World!

What is Closure?

A closure is the combination of a function and the lexical environment within which that function was declared.

Closure is an inner function that has access to outer(enclosing) function variables.

Closure has 3 scope chains:

  • has access to Own scope
  • has access to Outer function variables
  • has access to Global variables

we can access variables which are outside of function

Using closure

Closure are used for data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can’t get at the data from an outside scope except through the object’s privileged methods.

let see example of closure :

  function User(name){ 
     let displayAge = function(age){
        console.log(name + " is "+age+" year old.");
        }
      return  displayAge;
     }

  let user1 = User("John");
  user1("22") // Output : John is 22 year old.
Enter fullscreen mode Exit fullscreen mode


`

In above example , User() is the outer function that returns inner function displayAge(). Inner function has access to outer scope variable even though outer function is returned.

Conclusion

Closure are nothing but the inner or nested function that has access to variable that are in outer scope.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

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

Okay