Understand JavaScript closures in minutes | freeCodeCamp

I always forget what closures are, even if I continue to use them. The article makes a case for considering closures as stateful functions which is quite neat. Basically, closures allow a function to return another function (or functions); each returned function will also have access to any data that the original function had access to. In other words:

const add = function(x) {
    return function(y) {
        return x + y;
    }
}
const add10 = add(10);
add10(10); // 20

That will output 20 because the internal function has access to both variables. It's a bit freaky but it means you can define functions as reusable abstractions with preset variable values really easily. As the article points out, that can be a lot more secure and can help encapsulate sensitive data/functionality, like so:

const manageBankAccount = function(initialBalance) {
    let accountBalance = initialBalance;
    
    return {
        getBalance: function() { return accountBalance; },
        deposit: function(amount) { accountBalance += amount; },
        withdraw: function(amount) {
            if (amount > accountBalance) {
                return 'You cannot draw that much!';
            }

            accountBalance -= amount;
        }
    };
}

const accountManager = manageBankAccount(0);

accountManager.deposit(1000);
accountManager.withdraw(500);
accountManager.getBalance(); // 500

Explore Other Notes

Newer

The typos that changed lives

An elderly gent who inadvertently had his satnav set to "Rom" instead of "Rome" and wound up in the wrong country;A pilot that incorrectly input destination coordinates causing a […]

Older

Airbridge

A new calendar app without an implicit bias towards iOS is always worth celebrating. Airbridge certainly ticks the aesthetically-pleasing box and I quite like the idea of just defining time blocks as […]
  • I always forget what closures are, even if I continue to use them. The article makes a case for considering closures as <em>stateful functions</em> which is quite neat. Basically, closures allow a [&#8230;]
  • Murray Adcock.
Journal permalink

Made By Me, But Made Possible By:

CMS:

Build: Gatsby

Deployment: GitHub

Hosting: Netlify

Connect With Me:

Twitter Twitter

Instagram Instragram

500px 500px

GitHub GitHub

Keep Up To Date:

All Posts RSS feed.

Articles RSS feed.

Journal RSS feed.

Notes RSS feed.