Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Created July 30, 2020 13:36
Show Gist options
  • Save treyhuffine/4ca7126c8381b3b6d3c885fcdaab169a to your computer and use it in GitHub Desktop.
Save treyhuffine/4ca7126c8381b3b6d3c885fcdaab169a to your computer and use it in GitHub Desktop.
const outerFunction = () => {
let storedValue = 0;
// returning a function from a function is the key
return () => {
storedValue = storedValue + 1;
console.log('storedValue = ', storedValue);
};
};
// By executing outerFunction, we create a unique instance of the returned function with permanent access to a unique instance of the storedValue variable.
const functionWithPermanentAccessToStoredValue = outerFunction();
// The below line is important to note. Closures are created by functions being returned from other functions.
console.log(typeof functionWithPermanentAccessToStoredValue); // function
// By executing functionWithPermanentAccessToStoredValue, we increment storedValue. This happens because it has access to the storedValue since it was a nested function inside the outerFunction scope.
functionWithPermanentAccessToStoredValue(); // storedValue = 1
functionWithPermanentAccessToStoredValue(); // storedValue = 2
functionWithPermanentAccessToStoredValue(); // storedValue = 3
// storedValue is only accessible to the function that was returned from outerFunction which we have stored inside the variable functionWithPermanentAccessToStoredValue.
console.log(typeof storedValue); // undefined
// Accessing storedValue outside functionWithPermanentAccessToStoredValue is undefined
Closures:
- A closure is a function that was return from a wrapping/outer function and has permanent access to the variables created inside of the outer function scope.
- JavaScript is function scoped. Any variables created inside of a function
can only be accessed by that function or its nested functions.
- All variables created inside the outer function can be accessed permanently inside the function that we return.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment