I've been wondering for a while - what can JavaScript closures be used for?
I know how to write them and I know how they work, but I just can't get the idea of how they can be used.
function closure() {
var name = "John";
function displayName() {
return 'Hello, ' + name;
}
return displayName;
}
So far I only found one use for them - encapsulating data, so it won't be visible outside the function.
But what else can they be used for? Should I write OOP with closures? Do I need to put all my code inside a closure so it wont mess the global scope?
Any clarifications are highly appreciated!