0 day streak
javascript / intermediate
Snippet

Encapsulation with Private Class Fields

Using the '#' prefix before a property name makes it truly private to the class. It cannot be accessed or modified from outside the class instance, ensuring strict encapsulation.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class SecureVault {
#secretCode;
constructor(code) {
this.#secretCode = code;
}
verify(input) {
return this.#secretCode === input;
}
}
const vault = new SecureVault('1234');
console.log(vault.verify('1234')); // true
// console.log(vault.#secretCode); // SyntaxError
nodejs
Breakdown
1
#secretCode;
Declares a private field that is inaccessible outside the class scope.
2
this.#secretCode = code;
Assigns a value to the private field within the constructor.