In modern JavaScript, prefixing a class field with # makes it private:
class User {
#token = 'secret';
}
This isn’t just about access control. Bundlers like esbuild can safely rename #token
to something shorter — like #a
.
That means smaller bundles!
Compare this to public fields:
class User {
token = 'secret';
}
Here, token must stay as-is — even in production — because external code might rely on it.
Private fields, on the other hand, are guaranteed to be internal-only.
That gives bundlers the green light to compress them aggressively.
In large apps with many classes, switching to # private fields can save a surprising amount of space — especially when field names are long.
Bonus: It’s not just about size.
Private fields make your APIs cleaner and your code more robust.
TL;DR:
Use #
private fields.
Smaller bundles, safer code.
Gotcha:
- Supported in modern environments only.
- Can’t be accessed or tested from outside (even in unit tests) — by design!
Still, if you’re targeting evergreen browsers or bundling for modern platforms:
Top comments (2)
Saving this one for the books, thanks for the read. Definitely will keep this in mind during my next project.
Thanks, have a nice day :)
If you have time, please check out the link in the below.