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 …

  • <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p>I always forget what closures are, even if I continue to use them. The article makes a case for considering closures as&nbsp;<em>stateful functions</em> which is quite neat. Basically, closures allow a …</p> </body> </html>
  • Murray Adcock.
Journal permalink