DEV Community

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

Posted on

🚀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.

Top comments (0)