
π JavaScript Closures Explained with a Bank Account (Beginners, This One's for You!)
Ever wondered how a bank keeps your balance private β so no one else can just walk in and change it? That's exactly what a closure does in JavaScript. It locks your data away and only lets you touch it through specific actions β like a deposit or withdrawal. Let's break it down with a real banking example. π¦ 1. What Is a Closure? Imagine you open a bank account. The bank creates a private locker for you β your balance, your account number. No one else can access it directly. You can only interact with it through the bank's services: deposit, withdraw, check balance. In JavaScript, a closure is when an inner function "remembers" the variables from the outer function β even after the outer function has finished running. That's it. That's the whole idea. π 2. What Does the Code Look Like? Here's the full createAccount function we'll be working with: function createAccount ( userName , initialBalance ) { let balance = initialBalance ; // private let accountNumber = Math . floor ( Math . ra
Continue reading on Dev.to Webdev
Opens in a new tab


