Skip to content

Instantly share code, notes, and snippets.

@loriculberson
Last active February 15, 2021 18:37
Show Gist options
  • Save loriculberson/bb4061c6440066445a489bd5933d60d3 to your computer and use it in GitHub Desktop.
Save loriculberson/bb4061c6440066445a489bd5933d60d3 to your computer and use it in GitHub Desktop.
// Resources:
// https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8
// http://davidshariff.com/blog/javascript-scope-chain-and-closures/
// https://www.freecodecamp.org/news/lets-learn-javascript-closures-66feb44f6a44/
// Purpose: Used to provide data privacy
// Closure: The closure is a collection of all the variables in scope at the time of creation of the function.
// Here is how it works. Whenever you declare a new function and assign it to a variable,
// you store the function definition, as well as a closure. The closure contains all the variables
// that are in scope at the time of creation of the function. It is analogous to a backpack.
// A function definition comes with a little backpack. And in its pack it stores all the variables
// that were in scope at the time that the function definition was created.
// Video:
// https://www.youtube.com/watch?v=1JsJx1x35c0
// https://www.youtube.com/watch?v=-jysK0nlz7A
//data not private
var name = "Top Secret";
function hideMyName(name) {
function displayName() {
console.log('inside displayName')
return name;
}
return displayName;
}
//this will return the displayName function, but it's not invoked
hideMyName();
//data made private with a closure
function hideMyName() {
var name = "Top Secret";
function displayName() {
console.log('hello!!!', name);
return name;
}
return displayName;
}
var myHiddenName = hideMyName();
myHiddenName();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment