I'm trying my hardest to wrap my head around JavaScript closures.
I get that by returning an inner function, it will have access to any variable defined in its immediate parent.
Where would this be useful to me? Perhaps I haven't quite got my head around it yet. Most of the examples I have seen online don't provide any real world code, just vague examples.
Can someone show me a real world use of a closure?
Is this one, for example?
var warnUser = function (msg) {
var calledCount = 0;
return function() {
calledCount++;
alert(msg + '\nYou have been warned ' + calledCount + ' times.');
};
};
var warnForTamper = warnUser('You can not tamper with our HTML.');
warnForTamper();
warnForTamper();
JavaScript module pattern uses closures. Its nice pattern allowes you to have something alike "public" and "private" vars.
I know i am super late in answering this question but it might help anyone still searching for the answer in 2018.
Javascript closures can be used to implement throttle and debounce functionality in your application.
Throttling:
Throttling puts a limit on as a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."
Code :
Debouncing:
Debouncing put a limit on a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."
Code:
As you can see closures helped in implementing two beautiful features which every web app should have to provide smooth UI experience functionality.
I hope it will help someone.