What is a practical use for a closure in JavaScript?

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() {
       alert(msg + '\nYou have been warned ' + calledCount + ' times.');

var warnForTamper = warnUser('You can not tamper with our HTML.');

7 thoughts on “What is a practical use for a closure in JavaScript?”

  1. 396661 837056Nice post. I learn something much more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a bit something from their store. Id prefer to use some with the content on my weblog whether you dont mind. Natually Ill give you a link on your web blog. Thanks for sharing. 151276

  2. 119488 935057Currently it seems like BlogEngine will be the greatest blogging platform out there right now. (from what Ive read) Is that what youre using on your blog? 387925

  3. I loved as much as you’ll receive carried out right here.
    The sketch is attractive, your authored material
    stylish. nonetheless, you command get bought an shakiness over that you wish be
    delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you
    shield this hike.


Leave a Comment