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 encapsulation
1class BankAccount {
// # prefix makes the field truly private
// Cannot be accessed from outside the class
2 #balance = 0;
3
// Public method to add money
4 deposit(amount) {
// Only accept positive amounts
5 if (amount > 0) this.#balance += amount;
6 }
7
// Public method to remove money
8 withdraw(amount) {
// Validate: positive amount and sufficient funds
9 if (amount > 0 && amount <= this.#balance) {
10 this.#balance -= amount;
11 return amount;
12 }
// Return 0 if withdrawal fails
13 return 0;
14 }
15
// Getter method to safely access the balance
16 getBalance() {
17 return this.#balance;
18 }
19}
20
// Create account instance
21const account = new BankAccount();
// Deposit 100
22account.deposit(100);
// Withdraw 30
23account.withdraw(30);
// Output: 70
24console.log(account.getBalance());

Output

70
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.

  • ;× 10
  • (× 10
  • )× 10
  • .× 8
  • {× 5
  • }× 5
  • #× 5
  • =× 5
  • &× 2
  • >× 2

More JavaScript examples at level 5

← JavaScript typing practice