Skip to content

Instantly share code, notes, and snippets.

@itzzmeakhi
Created January 11, 2022 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itzzmeakhi/68d49a74d8ae98bf380aa61f7996d3b7 to your computer and use it in GitHub Desktop.
Save itzzmeakhi/68d49a74d8ae98bf380aa61f7996d3b7 to your computer and use it in GitHub Desktop.
function A() {
const msgFromOuterFn = 'I am from Outer function scope';
function B() {
console.log(msgFromOuterFn);
}
return B;
}
// A returns a function B, In JavaScript when ever any function completes its execution, its scope is removed from the heap. So all the variables declared in its scope won't be available once its execution is done.
const returnedFn = A();
// A() completed its execution, so the value msgFromOuterFn will not able available.
// With JS Closures, even the outer function completed execution, inner functions are able to access the outer functions scope.
console.log(returnedFn());
// Will print its value, instead of throwing an error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment