Skip to content

Instantly share code, notes, and snippets.

@suhailgupta03
Created August 8, 2023 14:49
Show Gist options
  • Save suhailgupta03/f0348912f69fa3b6a05cdd7945a528c9 to your computer and use it in GitHub Desktop.
Save suhailgupta03/f0348912f69fa3b6a05cdd7945a528c9 to your computer and use it in GitHub Desktop.
// closure is a function having access to the parent
// scope
function greet() {
var message = "Good evening";
function sayHi() {
console.log(message);
} // Here closure is created,
// sayHi function has access to message variable
return sayHi;
} // greet function is returning another function named sayHi
// sayHi is a function declared inside greet function
var fn = greet(); // returns sayHi function
fn(); // sayHi function is called
console.log(message); // message is not accessible here
// because message is not in the global scope
// the reason it is not in the global scope is because
// greet function has returned and it's execution context
// has been removed from the stack
// message here is also the private variable
// we call it as a private variable because it is not
// accessible outside the greet function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment