Interview Q&A / JavaScript

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How can you create private variables in JavaScript using closures?

SHORT ANSWER

Declare the variable inside a function and return only functions that use it. The variable lives on in the closure, but no outside code can read or change it directly.

Explain it simply

Think of a bank locker room. You cannot walk into the vault, but the clerk hands you two buttons: deposit and check balance. The money is private; the buttons are the public interface.

In code, the vault is a local variable in a function. When the function returns an object of methods, those methods keep access to the variable through their closure, even though the outer function has finished. Nothing else can reach it, because there is no property to touch.

Modern JavaScript also has class private fields (#balance), but closures work everywhere and are a very common interview question.

Example

js
function createWallet(start) {
  let balance = start;
  return {
    add(rupees) { balance += rupees; return balance; },
    get() { return balance; }
  };
}

const w = createWallet(100);
w.add(50);
console.log(w.get());       // Output: 150
console.log(String(w.balance));    // Output: undefined

Each call to createWallet makes a fresh, independent balance.

What to say in the interview

"A closure keeps a function's local variables alive after it returns. By returning only methods that use the variable, I get true privacy without naming conventions. Each call creates a separate private state. Class #private fields are the newer alternative."

Common mistakes

  • Exposing the variable as a property (this.balance) and assuming it is private.
  • Expecting two wallets to share one balance. Each call gets its own.

#javascript#closures

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.