"If you can't explain it to a six year old, you don't really understand it." - Richard Feynman
function foo(x) {
var y = x;
return function () {
return y;
}
}
A man goes on a long trip. Before leaving, he takes a snapshot of his house.
While he's away, the house is replaced with a condo. The man is unaware and continues to show the photo and describe his house to the people he meets.
var color = 'white';
function leaveHome () {
// a variable in leaveHome's scope
var description = "My house is " + color;
// returns another function, creating a closure over description
return function() {
console.log(description);
}
}
var travellingMan = leaveHome();
travellingMan(); // "My house is white"
color = 'red'; // They painted the house
travellingMan(); // "My house is white"