Private Fields in Classes
Private fields in JavaScript classes give you a way to hide data from outside code, reinforcing the principle of encapsulation. When you use the # symbol before a field name in a class, you create a private field. This means the field is only accessible within the class body itselfβcode outside the class cannot read or write to it directly. By restricting access to sensitive data, you prevent accidental modification and help keep your objects' internal state safe. This is especially important in situations where exposing data could lead to bugs or security issues.
123456789101112131415161718192021222324252627282930class BankAccount { #balance; // private field constructor(initialBalance) { this.#balance = initialBalance; } deposit(amount) { if (amount > 0) { this.#balance += amount; } } withdraw(amount) { if (amount > 0 && amount <= this.#balance) { this.#balance -= amount; return amount; } return 0; } getBalance() { return this.#balance; } } const account = new BankAccount(100); account.deposit(50); console.log(account.getBalance()); // 150 console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain why using private fields is important in JavaScript classes?
How do I access or modify a private field from outside the class?
Are there alternatives to private fields for encapsulation in JavaScript?
Awesome!
Completion rate improved to 6.25
Private Fields in Classes
Swipe to show menu
Private fields in JavaScript classes give you a way to hide data from outside code, reinforcing the principle of encapsulation. When you use the # symbol before a field name in a class, you create a private field. This means the field is only accessible within the class body itselfβcode outside the class cannot read or write to it directly. By restricting access to sensitive data, you prevent accidental modification and help keep your objects' internal state safe. This is especially important in situations where exposing data could lead to bugs or security issues.
123456789101112131415161718192021222324252627282930class BankAccount { #balance; // private field constructor(initialBalance) { this.#balance = initialBalance; } deposit(amount) { if (amount > 0) { this.#balance += amount; } } withdraw(amount) { if (amount > 0 && amount <= this.#balance) { this.#balance -= amount; return amount; } return 0; } getBalance() { return this.#balance; } } const account = new BankAccount(100); account.deposit(50); console.log(account.getBalance()); // 150 console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
Thanks for your feedback!