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: 1But trying to access the private method directly will cause an error:
myCounter.#increment(); // Error: Private method is not accessible outside classPrivate methods help maintain encapsulation by keeping internal implementation details hidden from the outside world.
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
trueif the text is not empty and less than 100 characters - Return
falseotherwise
Cheat sheet
Private methods in JavaScript classes are defined using the # prefix and can only be accessed from within the class:
class Counter {
#count = 0;
// Private method
#increment() {
this.#count++;
}
// Public method that uses the private method
addOne() {
this.#increment();
return this.#count;
}
}Private methods cannot be accessed from outside the class:
const myCounter = new Counter();
myCounter.addOne(); // Works
myCounter.#increment(); // Error: Private method is not accessiblePrivate methods help maintain encapsulation by hiding internal implementation details.
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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge