Javascript - Practical Uses of Closures
Code Life
By Pierre Marsaa
Private Variables with Closures
Imagine storing a player's gold in a normal variable or object property (wallet.gold = 100). Any bug in your program could accidentally set wallet.gold = -9999!
With a closure, you can keep gold completely private inside makeWallet and return an object containing only the methods allowed to interact with it:
↗️
Loading editor...
↶
↷
Notice that wallet.gold prints undefined: gold is not a property on the object! It lives safely inside the closure, where only wallet.earn() and wallet.total() can access it.
Verify