×

javascript · level 3 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Closures let you hide data behind a few safe functions.

Any line of code can change a plain object's properties, including a buggy one. A closure can keep a value instead: only the functions made inside the factory can reach it.

Here the factory returns an object holding two functions. They share one hidden balance. The rest of the program must go through them, and deposit can refuse bad amounts. This idea, data plus its guards and nothing else on show, is .

function makeWallet() {
  let balance = 0;
  return {
    deposit(amount) {
      if (amount <= 0) { return "Refused"; }
      balance = balance + amount;
      return "OK";
    },
    getBalance() { return balance; }
  };
}
const wallet = makeWallet();
console.log(wallet.deposit(20), wallet.deposit(-5), wallet.getBalance());
console.log(wallet.balance);

Inside an object, deposit(amount) { } is short for deposit: function (amount) { }.