Menu
Coddy logo textTech

Private Methods

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 19 of 56.

Private methods in JavaScript classes allow you to hide implementation details and prevent external access to internal functionality.

Starting in ES2022, private methods can be defined using the # prefix:

class Counter {
  #count = 0;
  
  // Create a private method
  #increment() {
    this.#count++;
  }
  
  // Public method that uses the private method
  addOne() {
    this.#increment();
    return this.#count;
  }
}

Let's create a Counter instance:

const myCounter = new Counter();

We can call the public method:

console.log(myCounter.addOne()); // Output: 1

But trying to access the private method directly will cause an error:

myCounter.#increment(); // Error: Private method is not accessible outside class

Private methods help maintain encapsulation by keeping internal implementation details hidden from the outside world.

challenge icon

Challenge

You're given a MessageBox class that stores messages. Your task is to add a private method called #isValidMessage(text) that validates messages. It should:

  • Return true if the text is not empty and less than 100 characters
  • Return false otherwise

Try it yourself

import { MessageBox } from './messageBox.js';

// Using the message box
const box = new MessageBox();

console.log(box.setMessage("Hello"));    // "Message set!" (uses #isValidMessage)
console.log(box.setMessage(""));         // "Invalid message!" (uses #isValidMessage)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming