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 # syntax
1class BankAccount {
// Private field - cannot be accessed outside class
2 #balance = 0;
3
// Deposit method - validates and updates balance
4 deposit(amount) {
5 if (amount > 0) this.#balance += amount;
// Return this for method chaining
6 return this;
7 }
8
// Withdraw method - checks sufficient funds
9 withdraw(amount) {
10 if (amount > 0 && amount <= this.#balance) this.#balance -= amount;
11 return this;
12 }
13
// Public getter for private balance
14 getBalance() {
15 return this.#balance;
16 }
17}
18
// Create account and chain operations
19const account = new BankAccount();
20account.deposit(100).deposit(50).withdraw(30);
// Get balance through public method: 120
21console.log(account.getBalance());

Output

120
Practice typing this code

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

More JavaScript examples at level 5

← JavaScript typing practice