Skip to main content

Welcome to a Grasp lesson

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

Lesson 37

Implementing Private Methods

This lesson is built with resources from youtube.com, developer.mozilla.org and 1 more site.

Hello! Welcome to the fifth lesson in our module on Advanced OOP.

In the previous lesson, we established the "why" and "how" of encapsulation by implementing private fields using the # syntax. You learned to hide a class's internal state, protecting it from unintentional external modification and creating a robust boundary between the class's implementation and its public interface.

Today, we'll extend this powerful concept from data to behavior. Our goal is to implement private methods within a class. Just as private fields hide internal data, private methods hide internal implementation logic. This is a cornerstone of creating clean, maintainable, and well-structured classes, a practice you're likely familiar with from other object-oriented design contexts. We'll explore how to define these methods, how they interact with the rest of the class, and how they complete our picture of true encapsulation in JavaScript.

The Case for Hiding Internal Logic

Imagine you're designing a complex component. You have a main public method, like generateReport(), that performs a series of steps: fetching data, validating it, formatting it, and then rendering the output. In procedural code, you might break these steps into separate helper functions. In OOP, the same principle applies, but we want to ensure these helper functions aren't exposed as part of the class's public API, where they could be called out of order or misused. They are implementation details, not features.

Let's revisit the Database class example, which perfectly illustrates this problem. The class has a clear public purpose—saveData—but its interface is cluttered with internal helper methods that a consumer of the class shouldn't need to know about, let alone call directly.

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

To solidify why private methods are necessary, let's re-examine this segment from the 'Tech with Nader' video. Pay close attention to the problems that arise when helper methods like initDBConnection and authorize are public.

Watch the segment from 11:26 to 23:19. Focus on how exposing internal methods leads to developer confusion (Which method do I call? In what order?) and risk (What happens if I call an internal method directly, or even reassign it?).

This scenario highlights a critical design flaw: a bloated and fragile public interface. The ideal solution is to hide these helper methods, making them private to the class.


Implementing and Using Private Methods

The syntax for creating a private method is beautifully consistent with what you learned for private fields: you simply prefix the method name with a hash (#).

A private method can only be called from within the body of the class that defines it. To call a private method from another (typically public) method in the same class, you use the this keyword, just as you would for a public method, but include the #.

Syntax:

  • Declaration: class MyClass { #privateHelper() { /* ... */ } }
  • Invocation: this.#privateHelper();

Let's see how this solves the problems in our Database class, creating a clean and safe public API.

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

Continuing with the same video, we'll now see the solution. The presenter refactors the Database class, converting the internal helper methods to private methods.

Watch from 23:19 to 34:47. Observe how #initDBConnection, #authorize, and #updateQuery are now inaccessible from outside the class. The only method available on a db instance is saveData, which is exactly the clean interface we want. Notice that the calls inside saveData are updated to this.#methodName().

Now that you've seen it in practice, let's consult the official documentation to solidify the technical details.

Private methods

The MDN Web Docs provide the definitive reference on private methods. This will clarify their behavior, including how they differ from public methods in relation to the class prototype.

Read the section titled 'Private methods', including the subsections on 'Private instance methods' and 'Private static methods'. Pay special attention to the bullet point stating that private instance methods are only available on instances of the class, not on its .prototype property. This is a key difference from public methods.


Deeper Dive: Private Methods and Advanced Scenarios

Understanding the core syntax is the first step. Now, let's consider how private methods behave in more complex scenarios, such as with inheritance and static contexts.

1. Privacy and Inheritance

As we discussed with private fields, JavaScript's privacy model is very strict. A private method is confined to the class that defines it and is completely inaccessible to subclasses. This enforces a strong encapsulation boundary, preventing a child class from meddling with the parent's internal implementation details.

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

Let's watch the final segment on this topic, which explicitly demonstrates what happens when a subclass tries to access a private method from its parent.

Watch from 35:15 to 40:10. The video shows a CustomDB class extending Database. Notice that the attempt to call super.#initDBConnection() from the subclass results in a syntax error. This confirms that privacy is class-scoped, not inheritance-scoped.

2. Private Static Methods

You can also combine the static and private modifiers. A private static method belongs to the class itself (not instances) and is only accessible from within the class body, typically from other public or private static methods.

This is useful for utility functions that are related to the class's overall functionality but don't depend on instance-specific state and shouldn't be exposed publicly.

Syntax:

  • Declaration: class MyClass { static #privateStaticHelper() { /* ... */ } }
  • Invocation: MyClass.#privateStaticHelper();

JavaScript Class Inheritance | Static And Private Methods In JavaScript

This short video from GreatStack provides a clear, focused explanation of private static methods.

Watch from 14:02 to 16:08. The example demonstrates how to declare a private static method and how to call it using the Class name from within another class method. This cleanly combines concepts you've learned in previous lessons.

Test your understanding!

You are building a TextAnalyzer class that provides statistics about a piece of text.

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

  1. The constructor should accept a string of text and store it in a private field #text.
  2. The class should have a public method getStats() that returns an object like { words: _count_, characters: _count_, sentences: _count_ }.
  3. The logic for counting words, characters, and sentences must be implemented in three separate private methods: #countWords(), #countCharacters(), and #countSentences().
  4. The public getStats() method should be the only way to get the analysis, and it must work by calling these three private helper methods.
class TextAnalyzer {
  #text;

  constructor(text) {
    if (typeof text !== 'string' || text.length === 0) {
      throw new Error("Invalid text provided.");
    }
    this.#text = text;
  }

  // TODO: Implement the private #countWords method.
  // A simple approach is to split the text by spaces.

  // TODO: Implement the private #countCharacters method.
  // This should be the raw length of the text string.

  // TODO: Implement the private #countSentences method.
  // A simple approach is to count '.', '!', and '?'.

  // TODO: Implement the public getStats method that uses the private helpers.
  getStats() {
    // ... your implementation here
  }
}
Show answer

Here is a possible solution that fulfills the requirements.

class TextAnalyzer {
  #text;

  constructor(text) {
    if (typeof text !== 'string' || text.length === 0) {
      throw new Error("Invalid text provided.");
    }
    this.#text = text;
  }

  // Private helper to count words
  #countWords() {
    return this.#text.trim().split(/\s+/).length;
  }

  // Private helper to count characters
  #countCharacters() {
    return this.#text.length;
  }

  // Private helper to count sentences
  #countSentences() {
    // This is a naive implementation, but fine for the exercise.
    const sentenceEndings = this.#text.match(/[.!?]+/g) || [];
    return sentenceEndings.length > 0 ? sentenceEndings.length : 1;
  }

  // Public method that orchestrates the private helpers
  getStats() {
    const wordCount = this.#countWords();
    const charCount = this.#countCharacters();
    const sentenceCount = this.#countSentences();

    return {
      words: wordCount,
      characters: charCount,
      sentences: sentenceCount,
    };
  }
}

// Example usage:
const analyzer = new TextAnalyzer("Hello world! This is a test. Is it working?");
const stats = analyzer.getStats();
console.log(stats); // Expected: { words: 9, characters: 48, sentences: 3 }

// These attempts would throw a SyntaxError:
// analyzer.#countWords();
// analyzer.#text;

This design is clean because the user of TextAnalyzer only needs to know about getStats(). The complex (or potentially changing) counting logic is hidden away in private methods, which can be modified or improved without affecting the public API.


Conclusion

You have now completed your understanding of JavaScript's native encapsulation features. By combining private fields for state and private methods for behavior, you can construct classes that are truly self-contained, robust, and easy to reason about.

Key Takeaways:

  • Private methods are declared by prefixing their name with # and are used to encapsulate internal logic that should not be part of the public API.
  • They are invoked from within the class using this.#methodName().
  • This practice leads to cleaner public interfaces and more maintainable code by separating concerns.
  • Like private fields, private methods are strictly class-scoped and are not accessible by subclasses.
  • Private static methods (static #methodName) provide a way to create class-level helper functions that are hidden from the outside world.

Next Up

With a solid grasp of instance members (public and private) and static members, our next lesson will introduce a specialized feature that ties these concepts together: static initialization blocks. These blocks allow you to perform complex, one-time setup logic for a class when it is first defined, which is perfect for configuring static properties or setting up connections required by static methods.