Private Class Fields in JavaScript
Level 5371 keystrokes
Uses private class fields (#) to encapsulate the balance, accessible only through methods.
JavaScript code
// Define a class with encapsulation1class BankAccount { // # prefix makes the field truly private // Cannot be accessed from outside the class2 #balance = 0;3 // Public method to add money4 deposit(amount) { // Only accept positive amounts5 if (amount > 0) this.#balance += amount;6 }7 // Public method to remove money8 withdraw(amount) { // Validate: positive amount and sufficient funds9 if (amount > 0 && amount <= this.#balance) {10 this.#balance -= amount;11 return amount;12 } // Return 0 if withdrawal fails13 return 0;14 }15 // Getter method to safely access the balance16 getBalance() {17 return this.#balance;18 }19}20 // Create account instance21const account = new BankAccount();// Deposit 10022account.deposit(100);// Withdraw 3023account.withdraw(30);// Output: 7024console.log(account.getBalance());Output
70
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
;× 10(× 10)× 10.× 8{× 5}× 5#× 5=× 5&× 2>× 2