Closures Flashcards
What is a closure?
It’s a feature that allows a function to remember the variables and functions that were present in its parent scope, even after the parent function has returned.
What is the purpose of closures?
They provide a mechanism to access variables from an outer function in an inner function, enabling data privacy and the ability to maintain state. They are a powerful tool for creating modular and reusable code.
Data privacy:
By creating functions that have access to variables from their parent scope, closures allow you to create private variables and functions that are not directly accessible from outside.
Private variables:
Achieve this by implementing data hiding, and maintaining state in functional programming. They enable the concept of “lexical scoping,” where functions remember the variables in their scope when they were defined.
What is the difference between a closure and a regular function?
A closure has access to variables in its outer lexical scope
A regular function does not.
Closures are created when a function is declared inside another function, whereas regular functions are standalone functions.