Junior — Middle
How is data hiding implemented inside a class and why is it important?
sobes.tech AI
Answer from AI
Data hiding within a class in Node.js is achieved through scope and encapsulation mechanisms. In JavaScript (and Node.js), you can use:
- Local variables inside constructor functions or modules, which are inaccessible from outside.
- Symbols or private class fields (with the # prefix in modern versions).
This is important for protecting the internal state of an object from direct access and modification from outside, helping to prevent unforeseen errors and maintain class invariants.
Example with a private class field:
class User {
#password;
constructor(name, password) {
this.name = name;
this.#password = password;
}
checkPassword(input) {
return input === this.#password;
}
}
const user = new User('Alice', 'secret');
console.log(user.checkPassword('secret')); // true
console.log(user.#password); // SyntaxError: Private field '#password' must be declared in an enclosing class
Thus, internal data is protected from direct access.