Course contentsShow
← JavaScript
Lesson 791 of 2,72318. ClassesFree lesson

Private Methods

Discover how to create private instance methods with # that are only callable within the class body.

Private Methods

What you'll learn: How to create private instance methods using the # symbol that can only be called from inside your class.

Why Private Methods Matter

Just like private fields keep data hidden, private methods keep internal helper logic hidden from code outside the class. They're part of your class's "secret recipe"—functionality that supports your public methods but shouldn't be called directly by users of your class.

Creating Private Methods

Use the # symbol before the method name to make it private:

class BankAccount {
  #balance = 0;

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

  #isValidAmount(amount) {
    // Private helper method - only callable inside this class
    return typeof amount === 'number' && amount > 0;
  }
}

const account = new BankAccount();
account.deposit(100);           // ✓ Works
// account.#isValidAmount(50);  // ✗ SyntaxError: Private field '#isValidAmount' must be declared in an enclosing class

How They Work

Private methods:

  • Cannot be called from outside the class body
  • Cannot be accessed by subclasses
  • Can call other private methods and access private fields
  • Are defined on the instance (not the prototype)
  • Follow the same # naming convention as private fields

Real-World Example

class PasswordValidator {
  #minLength = 8;

  isValid(password) {
    return this.#hasMinLength(password) && 
           this.#hasSpecialChar(password);
  }

  #hasMinLength(pwd) {
    return pwd.length >= this.#minLength;
  }

  #hasSpecialChar(pwd) {
    return /[!@#$%^&*]/.test(pwd);
  }
}

The helper methods #hasMinLength and #hasSpecialChar are implementation details—users only need isValid().

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