Private Class Fields in JavaScript
Level 5371 keystrokes
Private class fields (with #) provide true encapsulation, accessible only within the class.
JavaScript code
// Class with private field using # syntax1class BankAccount { // Private field - cannot be accessed outside class2 #balance = 0;3 // Deposit method - validates and updates balance4 deposit(amount) {5 if (amount > 0) this.#balance += amount; // Return this for method chaining6 return this;7 }8 // Withdraw method - checks sufficient funds9 withdraw(amount) {10 if (amount > 0 && amount <= this.#balance) this.#balance -= amount;11 return this;12 }13 // Public getter for private balance14 getBalance() {15 return this.#balance;16 }17}18 // Create account and chain operations19const account = new BankAccount();20account.deposit(100).deposit(50).withdraw(30);// Get balance through public method: 12021console.log(account.getBalance());Output
120
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.
(× 11)× 11;× 9.× 9#× 5=× 5{× 4}× 4&× 2>× 2