Course contentsShow
← JavaScript
Lesson 1987 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Private Methods

Declaring private instance methods using # and when to use them for internal logic.

Private Methods

What you'll learn: How to declare truly private instance methods using the # syntax and when they're useful for hiding internal logic.

What Are Private Methods?

Just like private fields let you hide data inside a class, private methods let you hide behavior—functions that should only be accessible within the class itself. They use the same # prefix syntax you learned for private fields.

Private methods are perfect for internal helper functions that implement details you don't want exposed as part of your class's public API.

Declaring Private Methods

class BankAccount {
  #balance = 0;

  deposit(amount) {
    if (this.#isValidAmount(amount)) {
      this.#balance += amount;
      return true;
    }
    return false;
  }

  #isValidAmount(amount) {
    return typeof amount === 'number' && amount > 0;
  }
}

const account = new BankAccount();
account.deposit(100);           // ✅ Works
// account.#isValidAmount(50);  // ❌ SyntaxError: Private method not accessible

When to Use Private Methods

Private methods shine when you need internal logic that:

  • Implements details users shouldn't care about
  • Could change without breaking external code
  • Would clutter your public interface if exposed
  • Needs access to private fields

Think of them like backstage passes—employees can go backstage, but the audience can't. The #isValidAmount method is backstage work; only deposit (the public method) needs to know it exists.

Key Takeaway: Private methods declared with # create truly encapsulated helper functions that can only be called from inside the class, protecting internal implementation details from external code.