Closure is a powerful concept that combines a function with its surrounding environment (This environment is also called lexical environment) at the time the function was created. This environment includes all the variables and functions that were accessible to the inner function when it was created. Even after the Outer function has finished executing, the inner function can still access and manipulate these variables.
Ex: - Imagine we want to create a function that generates a secret a secret message. this message could be anything discount coupon code or Personalized greeting messages. but we don't want to store the message directly on the code.
function createSeceretMessage(secret){
let message = secret;
function revealMessage(){
console.log(message)
}
return revealMessage
}
const getSecretMessage = createSeceretMessage("This is Top secret message don't tell anyone!"))
getSecretMessage(); // output: This is Top secret message don't tell anyone!
Benefits of Closure
Data Hiding: Closures create private variables that can't be directly modified and accessed from outside the closure. (Promoting better Encapsulation)
Module Pattern: Closures are often used to create module patterns which allow us to create self-contained and reusable components with provided data or methods. (Promoting code organization and reusability)
Event Listeners: Closures are frequently used with event listeners to preserve state information between event triggers.