JavaScript Interview Question #112

What are private class fields in JavaScript?

Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate

Quick Interview Answer

Private class fields use names beginning with # and can be accessed only from code inside the declaring class. They provide language-enforced encapsulation rather than relying only on naming conventions.

Detailed Explanation

Private class fields use names beginning with # and can be accessed only from code inside the declaring class. They provide language-enforced encapsulation rather than relying only on naming conventions.

Private fields are different from ordinary properties whose names happen to start with an underscore. Attempting to access a private field directly outside the class is a syntax error.

Code Example

class BankAccount {
    #balance = 0;

    deposit(amount) {
        this.#balance += amount;
    }

    getBalance() {
        return this.#balance;
    }
}

const account = new BankAccount();
account.deposit(100);

console.log(account.getBalance()); // 100