Skip to content

Private Variables

A private variable is data that only an object’s own methods can read or change. JavaScript offers two ways to make one. A closure keeps a variable inside a function so that only the functions created there can reach it, and a private class field, written with a # in front of its name, is part of the language’s class syntax. Either way, outside code has to go through the methods you provide, which can check values and keep the object’s data consistent.

A leading underscore, as in _balance, is only a hint to other programmers. The property is as public as any other:

const account = {
_balance: 100,
deposit(amount) {
this._balance += amount;
},
};
account._balance = -5000;
console.log(account._balance);

This prints:

-5000

A variable declared inside a function lives on for as long as any function created inside it still exists, and those inner functions are the only code that can see it. This is a closure. Wrapping the function in an IIFE, an immediately invoked function expression, creates a single object whose data is hidden:

const counter = (() => {
let count = 0;
return {
increment() {
count += 1;
return count;
},
get value() {
return count;
},
};
})();
counter.increment();
counter.increment();
console.log(counter.value);
console.log(counter.count);
console.log(Object.keys(counter));

This prints:

2
undefined
[ 'increment', 'value' ]

count is not a property of counter, so counter.count is undefined and it does not appear in the list of keys. The only way to change it is increment(), and the getter value lets outside code read it but not set it. Getters & Setters explains get.

When more than one object is needed, call the outer function by name instead of running it once. Each call creates a fresh closure, so each object has its own private data:

function createTodoList() {
const items = [];
return {
add(text) {
items.push({ text, done: false });
},
complete(index) {
items[index].done = true;
},
get remaining() {
return items.filter((item) => !item.done).length;
},
};
}
const home = createTodoList();
const work = createTodoList();
home.add('Water the plants');
home.add('Book a dentist');
work.add('Send the invoice');
home.complete(0);
console.log(home.remaining, work.remaining);

This prints:

1 1

The two lists do not share items, because each call to createTodoList declared a new one. The cost is that every object gets its own copy of each method, which matters only when creating very large numbers of them.

Classes have private fields and methods built in, since ES2022. A name starting with # can be used only inside the class body that declares it:

class Account {
#balance = 0;
deposit(amount) {
if (amount <= 0) throw new RangeError('Deposit must be positive');
this.#balance += amount;
}
get balance() {
return this.#balance;
}
static hasBalance(obj) {
return #balance in obj;
}
}
const savings = new Account();
savings.deposit(250);
console.log(savings.balance);
console.log(savings['#balance']);
console.log(Object.keys(savings));
console.log(Account.hasBalance(savings), Account.hasBalance({}));

This prints:

250
undefined
[]
true false

savings['#balance'] looks for an ordinary property whose name happens to start with #, which does not exist, so it is undefined. Private fields never appear in Object.keys, for...in or JSON.stringify. The check #balance in obj tells whether an object was built by this class, without throwing an error for one that was not.

Using a private name outside its class is not a runtime error but a syntax error, so the file does not run at all:

class Account {
#balance = 0;
}
const a = new Account();
a.#balance = 10;

Running this stops with:

SyntaxError: Private field '#balance' must be declared in an enclosing class

Methods can be private too, which keeps helper code out of the class’s public interface:

class Timer {
#started = null;
#now() {
return 1000;
}
start() {
this.#started = this.#now();
return this.#started;
}
}
console.log(new Timer().start());

This prints:

1000

For classes, use # fields, because they are clear, checked by the engine and shared methods stay on the prototype. Closures remain the natural choice for objects built by plain functions, and for code written before private fields were supported. Neither is a security boundary, since anyone with access to the page can read the source, but both stop other code from depending on, or breaking, data it should not touch.

Steve Griffith covers this topic in his video Private Variables in JavaScript.