Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 36

Encapsulation with Private Class Fields

This lesson is built with resources from youtube.com, javascripttutorial.net and 1 more site.

Hello! Welcome to the fourth lesson in our module on Advanced OOP and Encapsulation.

In our previous lesson, we explored static methods and properties, which belong to the class itself rather than to any individual instance. However, a key characteristic of everything we've built so far—whether instance or static—is that it has been public. Any code outside our class could freely access and modify its properties and methods.

Today, we will address one of the most fundamental principles of Object-Oriented Programming: encapsulation. We'll move beyond convention and learn how to achieve true encapsulation using private class fields with the # syntax. This will allow us to hide internal state and implementation details, creating more robust, secure, and maintainable classes.

The "Why" of Encapsulation

At its core, encapsulation is about bundling the data (properties) and the methods that operate on that data into a single unit (a class), and restricting direct access to an object's internal components. It's about creating a clear public interface while hiding the complex machinery inside.

Encapsulation and "static" - Classes and Object Oriented Programming (OOP) - Javascript In Depth

To build a strong mental model of encapsulation, let's watch this excellent explanation from the 'Tech with Nader' channel. It uses real-world analogies like coffee machines and cars to illustrate why hiding internal complexity is so powerful.

Watch the segment from 2:17 to 10:03. Focus on the core idea: you can be an expert user of a complex object (like a car) through a simple interface (steering wheel, pedals) without needing to know anything about its internal engineering.


The Problem with "Private by Convention"

Before modern JavaScript features, developers relied on a convention: prefixing a property or method name with an underscore (e.g., this._internalValue). This was a signal to other developers: "This is an internal part of the class; please don't touch it."

However, this is merely a convention. The language does not enforce it. Any external code can still access and modify _internalValue, potentially breaking the class's invariants and leading to unpredictable behavior. Given your background in software engineering, you know that relying on convention alone for critical boundaries is fragile.

Encapsulation and "static" - Classes and Object Oriented Programming (OOP) - Javascript In Depth

Let's see a practical example of why this 'soft privacy' is problematic. The same video now demonstrates a Database class where internal helper methods are unintentionally exposed to the outside world, causing confusion and risk.

Watch from 11:26 to 23:19. Notice how the public interface of the Database class is cluttered with internal methods like initDBConnection and authorize. A developer using this class might call them incorrectly, reassign them, or modify internal properties like token, leading to bugs.


The Solution: True Privacy with Hash Names (#)

To solve this problem, ES2022 introduced a syntax for truly private class members. By prefixing a field or method name with a hash (#), you make it inaccessible from outside the class. This isn't a convention; it's a rule enforced by the JavaScript engine.

JavaScript Private Class Fields and Methods Example
This image provides a clear visual of the syntax. The `#` prefix marks `hashMeansPrivate` and `#methodsCanBePrivateNowToo()` as private, while `noHashIsPublic` remains public.

Let's see this in action. We'll watch a short, practical demonstration of converting a class from using public properties to truly private ones.

ES2022: Class Private Fields and Methods

This video from 'All Things JavaScript, LLC' provides a concise before-and-after. It starts with a class that has the exact problem we've been discussing and refactors it to use private fields and methods.

Watch the following segments: The Problem (0:52 - 4:40): See how the _count property can be modified from outside the class, violating its design. The Fix (5:31 - 7:07): Observe how _count and _greeting are converted to #count and #greeting. The Result (7:07 - 8:28): Notice that attempting to access #count from outside now results in a SyntaxError. Private Methods (8:28 - 9:42): Finally, see how the internal increaseCount method is also made private to complete the encapsulation.

As you saw, the key difference is the outcome of an access violation:

  • myObject._privateProperty = 123; // Works, but breaks convention.
  • myObject.#privateProperty = 123; // Fails with a SyntaxError.

This "hard privacy" is a compile-time (or, more accurately, parse-time) check. The engine knows before the code even runs that the access is illegal.


Private Members: The Technical Details

Now that we understand the what and why, let's dive into the specifics. The term "private properties" is slightly misleading; MDN refers to them as private elements because they behave differently from standard JavaScript properties.

Private elements - JavaScript - MDN Web Docs

The MDN Web Docs provide the definitive guide on private elements. This reading will solidify your understanding of the syntax rules and their precise behavior.

Read the introductory section and the 'Description' section. Pay close attention to these key points: Private elements are declared with # and must be declared in the class body. They cannot be dynamically accessed with bracket notation (e.g., this['#field']). Accessing a private field on an object that doesn't have it throws a TypeError, not undefined. You can check for the existence of a private field on an object using the in operator (e.g., #myField in myObject).


Encapsulation and Inheritance

A crucial aspect of JavaScript's private members, which distinguishes them from private or protected in languages like Java or C++, is their relationship with inheritance.

A private field or method is strictly confined to the class that defines it. It is NOT accessible by subclasses.

JavaScript Private Fields

Let's reinforce this important rule with a clear example from javascripttutorial.net.

Read the short section titled 'Private fields and subclasses'. It shows a Cylinder class extending a Circle class and explains why the Cylinder cannot access the #radius field from Circle.

This strict privacy model ensures that a subclass cannot accidentally interfere with the internal state of its parent class, leading to a stronger form of encapsulation.


Providing Controlled Access: Getters and Setters

Making a field private doesn't mean its value is locked away forever. It means the class is now in complete control of how that value is exposed or changed. The standard pattern is to provide public get and set accessors.

This allows you to:

  • Expose a read-only version of a property (by providing only a getter).
  • Perform validation or logging inside a setter before changing the internal value.
  • Compute a derived value in a getter.

JavaScript Private Fields

The Circle class example from our previous reading also demonstrates this pattern perfectly.

Now read the section 'Using getter and setter to access private fields'. Notice how the public radius setter includes validation logic before assigning a value to the private #radius field.

Test your understanding!

You are building a UserProfile class for a web application. The class needs to store a user's username (public), email (private), and creationDate (private).

Your task is to implement this class with the following requirements:

  1. The email and creationDate should be private fields.
  2. The email should be set only once at construction and should not be changeable afterward. Provide a public getter for it.
  3. The class should have a private method #getYearsSinceCreation() that calculates how many years have passed since the account was created.
  4. The class should have a public method getProfileSummary() that returns a string like: "User: [username], Email: [email], Member for [X] years.", using the private helper method.
class UserProfile {
  // Public field
  username;
  
  // TODO: Declare private fields for email and creationDate

  constructor(username, email) {
    this.username = username;
    // TODO: Initialize private fields
    // creationDate should be the current date
  }

  // TODO: Add a public getter for the email

  // TODO: Implement the private helper method #getYearsSinceCreation

  // TODO: Implement the public method getProfileSummary
}
Show answer

Here is a possible solution:

class UserProfile {
  username;
  #email;
  #creationDate;

  constructor(username, email) {
    this.username = username;
    this.#email = email;
    this.#creationDate = new Date();
  }

  // Public getter provides read-only access to the private email
  get email() {
    return this.#email;
  }

  // Private helper method for internal logic
  #getYearsSinceCreation() {
    const today = new Date();
    const diff_ms = today.getTime() - this.#creationDate.getTime();
    const years = diff_ms / (1000 * 60 * 60 * 24 * 365.25);
    return Math.floor(years);
  }

  // Public method that uses both public and private members
  getProfileSummary() {
    const memberYears = this.#getYearsSinceCreation();
    return `User: ${this.username}, Email: ${this.email}, Member for ${memberYears} years.`;
  }
}

// Example usage:
const user = new UserProfile('code_master', 'test@example.com');

console.log(user.username); // 'code_master'
console.log(user.email); // 'test@example.com'
console.log(user.getProfileSummary()); // "User: code_master, Email: test@example.com, Member for 0 years."

// These would all throw a SyntaxError:
// user.#email = 'new@email.com';
// console.log(user.#creationDate);
// user.#getYearsSinceCreation();

Conclusion

You have now mastered a crucial tool for writing robust, object-oriented JavaScript. By moving from convention-based privacy to language-enforced encapsulation, you can build classes that are more secure, less prone to bugs, and easier for other developers to use correctly.

Key Takeaways:

  • Encapsulation is the principle of hiding internal implementation details and exposing a clear public API.
  • The old _ prefix was a convention; the new # prefix is a language rule for creating truly private class fields and methods.
  • Attempting to access a private member from outside its class results in a SyntaxError.
  • Private members are not inherited by subclasses, ensuring the parent class's integrity.
  • You can provide controlled access to private data using public getters and setters, allowing for validation and read-only behavior.

Next Up

Today we covered the syntax and core concepts for both private fields and methods. In the next lesson, we will focus more specifically on the practical application and design patterns for implementing private methods. We'll explore how they help in breaking down complex logic and creating cleaner, more maintainable internal class structures.