# Encapsulation in JavaScript: Real Private Data, Not Just a Convention

## How do you make data really private in JavaScript?

Use `#private` class fields, closures or ES modules. Each of them hides data in a different way, and for many years JavaScript had no real private data at all.

Encapsulation means keeping an object's data together with the code that works on it, and hiding the details from the outside. Other code talks to the object only through a small public interface. Thanks to this, the object can protect its own rules, and you can change its inside later without breaking the rest of the app.

Many languages have a `private` keyword for this. JavaScript got real privacy late, so there are several ways to do it. In this post I show each of them and explain when to use which.

I will use the `Player` example again, a player with a nickname and a level. The rule is simple: nobody from the outside should be able to set the level to `-5` or to `'banana'`.

## Before classes: underscore and closures

### The underscore convention

The oldest trick is a name that starts with `_`. It tells other developers: "please do not touch this".

```js
class Player {
    constructor(nickname, level) {
        this._nickname = nickname;
        this._level = level;
    }
}

const player = new Player('Neo', 1);
player._level = -5;
console.log(player._level);
// Output: -5
```

This is only a convention. JavaScript does not block anything, so it is a message to people, not protection.

### Closures and factory functions

A closure gives you real privacy. A variable declared inside a function is not visible outside of it, but the functions created inside can still use it.

```js
function createPlayer(nickname) {
    let level = 1; // private, no one can reach it directly

    return {
        getNickname: () => nickname,
        getLevel: () => level,
        levelUp() {
            level += 1;
        },
    };
}

const player = createPlayer('Neo');
player.levelUp();
console.log(player.getLevel());
// Output: 2

console.log(player.level);
// Output: undefined
```

There is no way to read or change `level` except through the methods you gave. This works in every JavaScript version. The price is that every object gets its own copy of each method, which uses more memory when you create thousands of objects, and it does not work with `class` and `instanceof`.

## Private class fields with

Modern JavaScript (ES2022) has real private fields. A name that starts with `#` can be used only inside the class body. This is enforced by the language itself, not by a convention.

```js
class Player {
    #level = 1;

    constructor(nickname) {
        this.nickname = nickname;
    }

    levelUp() {
        this.#level += 1;
    }

    get level() {
        return this.#level;
    }
}

const player = new Player('Neo');
player.levelUp();

console.log(player.level);
// Output: 2

console.log(player.#level);
// Output: SyntaxError: Private field '#level' must be declared in an enclosing class
```

Notice that the error comes before the code runs. It is a syntax error, so you cannot even try to read the field from outside. `player['#level']` does not work either, it simply gives `undefined` because it is a normal property name, not the private field.

Private fields are supported in all modern browsers and in current Node.js versions, so you can use them in most new projects.

## Private methods, static members and the #x in obj check

The `#` works for methods too. This is a great way to hide helper code that only the class itself should call.

```js
class Player {
    static #playersCount = 0;
    #level = 1;

    constructor(nickname) {
        this.nickname = nickname;
        Player.#playersCount += 1;
    }

    static get count() {
        return Player.#playersCount;
    }

    levelUp() {
        this.#level += 1;
        this.#logLevel();
    }

    #logLevel() {
        console.log(`${this.nickname} is now level ${this.#level}`);
    }

    static isPlayer(value) {
        return #level in value;
    }
}

const player = new Player('Neo');
player.levelUp();
// Output: Neo is now level 2

console.log(Player.count);
// Output: 1

console.log(Player.isPlayer(player));
// Output: true

console.log(Player.isPlayer({}));
// Output: false
```

There are three things worth remembering here:

- **Private methods** (`#logLevel`) are part of the hidden implementation. You can rename or remove them later without breaking any code outside the class.
- **Static private fields** (`static #playersCount`) belong to the class, not to a single object.
- `#level in value` checks if an object really was created by this class. It is a safe way to do a "brand check" and it works even if somebody fakes the `constructor` property.

## Getters and setters that protect your data

Hiding a field is only half of the job. Usually the outside world still needs to read or change it, but under your rules. This is where getters and setters help. A setter can validate the value before it is saved.

```js
class Player {
    #level = 1;

    get level() {
        return this.#level;
    }

    set level(value) {
        if (!Number.isInteger(value) || value < 1) {
            throw new RangeError('Level must be a positive integer');
        }
        this.#level = value;
    }
}

const player = new Player();
player.level = 10;
console.log(player.level);
// Output: 10

player.level = -5;
// Output: RangeError: Level must be a positive integer
```

From outside it looks like a normal property (`player.level`), but there is a guard behind it. If you leave out the setter, the property is read only. In normal (non-strict) code a write is silently ignored, and in strict mode (and in ES modules) it throws a `TypeError`.

A good rule: do not create a getter and setter for every field automatically. Expose only what the outside world really needs, and prefer methods with a clear meaning, like `levelUp()`, over a bare `set level()`.

## ES modules: encapsulation on the file level

Encapsulation is not only about classes. Every ES module (a file loaded with `import` and `export`) has its own scope. Everything you do not export stays private to that file.

```js
// player-store.js
const players = new Map(); // private, not exported

function normalize(nickname) {
    return nickname.trim().toLowerCase();
}

export function addPlayer(nickname) {
    players.set(normalize(nickname), { nickname, level: 1 });
}

export function getPlayerLevel(nickname) {
    return players.get(normalize(nickname))?.level;
}
```

```js
// app.js
import { addPlayer, getPlayerLevel } from './player-store.js';

addPlayer('  Neo ');
console.log(getPlayerLevel('neo'));
// Output: 1
```

The rest of the app can use `addPlayer` and `getPlayerLevel`, but it cannot touch the `players` map or the `normalize` helper. The exported functions are the public interface, and everything else is an implementation detail you can change at any time.

This is the most common way to encapsulate code in a real frontend project, and it works well together with private class fields.

## Common mistakes

### 1\. Thinking TypeScript `private` is real privacy

The TypeScript keyword `private` is checked only when you compile. After compilation it is a normal public property, so JavaScript code can read it. If you need privacy at runtime, use `#`.

```ts
class Player {
    private level = 1; // TypeScript only
    #secret = 'x';     // real private field
}

const player = new Player();
console.log((player as any).level);
// Output: 1 (works at runtime)
```

### 2\. Returning a private object by reference

A private field does not protect the object stored inside it, if you return that object directly.

```js
class Team {
    #players = ['Neo', 'Trinity'];

    get players() {
        return this.#players; // leaks the real array
    }
}

const team = new Team();
team.players.push('Agent Smith');
console.log(team.players);
// Output: ['Neo', 'Trinity', 'Agent Smith']
```

Return a copy (`[...this.#players]`) or a frozen array instead.

### 3\. Expecting private fields to be inherited or serialized

A subclass cannot read the `#fields` of its parent. And `JSON.stringify` skips private fields, so they will not appear in your JSON. If you need to save the state, write an explicit method such as `toJSON()`.

### 4\. Hiding too much

Encapsulation is not about making everything private. If a field is safe to change from outside and has no rules, a normal public property is perfectly fine. Hide what can break the object, and keep the public interface small and simple.

## Which technique should I use?

For new code, use `#` private fields inside classes and ES modules for file-level privacy. Use the other techniques only when you have a special reason.

| Technique | Really private? | Works with `class` | Notes |
| --- | --- | --- | --- |
| `_underscore` name | No | Yes | Only a message to other developers |
| Closure / factory function | Yes | No | Works everywhere, but each object gets its own methods |
| `#private` fields and methods | Yes | Yes | Best choice today (ES2022) |
| ES module (no `export`) | Yes (per file) | Yes | Hides helpers and state from the rest of the app |

## Summary

Encapsulation in JavaScript means keeping the inside of an object or module hidden and offering a small, safe interface. Today the best tools are `#private` fields and methods in classes, validation in getters and setters, and ES modules that export only what is needed. Closures still work well for simple cases, while `_underscore` and TypeScript `private` only suggest privacy and do not enforce it. Remember to hide what can break your object, and not more than that.
