Closures in javaScript

what is a closure and how it works?

In computer programming, closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created.

A closure allows the function to access and manipulate variables that are external to that function. A key feature of closures is that they can remember the environment in which they were created, even if that environment no longer exists. This is known as lexical scoping.

Pros

  • Allows for data encapsulation
  • Improves code organisation
  • Creates private variables
  • Allows for partial application of functions

Cons

  • May lead to confusion and complexity
  • May create unexpected behaviour
  • Variables may be unintentionally overwritten

Conclusion

Closure can be used in a number of cases, such as creating a private variable, creating a function that has access to variables outside of its scope, or creating a function that can be passed around and invoked at a later time.

This is a quick rundown on what is closure for more info please check out MDN docs on closure.

If there is any issue with the explanation feel free to comment it.