Back to Blog
JavaScriptClassesPrivate FieldsEncapsulation

JavaScript Private Class Fields Guide

Master JavaScript private class fields with # syntax for true encapsulation and data privacy.

B
Bootspring Team
Engineering
October 18, 2019
6 min read

Private class fields use the # prefix for true encapsulation. Here's how to use them effectively.

Basic Syntax

Loading code block...

Private Methods

Loading code block...

Private Static Fields

Loading code block...

Private Accessors

Loading code block...

Checking for Private Fields

Loading code block...

Private Fields in Inheritance

Loading code block...

Factory Pattern with Privacy

Loading code block...

State Machine

Loading code block...

Immutable Configuration

Loading code block...

Observable with Private State

Loading code block...

Best Practices

Usage: ✓ Use # for true privacy ✓ Keep sensitive data private ✓ Hide implementation details ✓ Use private methods for internals Patterns: ✓ Validation in private methods ✓ State management ✓ Factory methods ✓ Encapsulated logic Benefits: ✓ True encapsulation ✓ No naming conventions needed ✓ Cannot be accessed externally ✓ Safe from prototype pollution Avoid: ✗ Private fields in object literals ✗ Accessing via ['#name'] ✗ Exposing private data in methods ✗ Over-privatizing everything

Conclusion

Private class fields with # provide true encapsulation in JavaScript. They cannot be accessed or modified from outside the class, making them ideal for sensitive data and internal implementation. Use private methods for validation and internal logic, and remember that each class has its own private namespace even in inheritance.

Share this article

Help spread the word about Bootspring

Related articles