Mimic OOP
Closures let you save state. We can use closure with JavaScript objects to mimic objects in Object-Oriented programming (encapsulation: private state + behavior). Here is an example:
function createAccount(initialBalance = 0) { let balance = initialBalance; return { deposit: function(amount) { balance += amount; }, withdraw: function(amount){ balance -= amount; }, getBalance: function() { return balance; } } } // Create any number of accounts const checking = createAccount(); const saving = createAccount(1000); saving.withdraw(200); checking.deposit(200); console.log(checking.getBalance()); console.log(saving.getBalance());
Modern JavaScript has Classes (to create objects) similar to Java and C++. JavaScript Classes are, in fact, functions. The process shown above is the underlying mechanics used by JavaScript to mimic Object-Oriented Programming.