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