Created
August 8, 2023 14:49
-
-
Save suhailgupta03/f0348912f69fa3b6a05cdd7945a528c9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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