Private Fields in Constructors
You'll learn how to properly initialize private fields inside constructors and understand the declaration order rules that come with them.
The Core Idea
When you use private fields (those with # names), you must declare them at the top of your class body before you can use them anywhere—including in the constructor. Unlike regular properties, you can't just assign a private field in the constructor without first declaring it.
Think of it like buying furniture: you need to reserve a specific spot in your room (declare the field) before you can actually place the furniture there (initialize it in the constructor).
Declaration Then Initialization
class BankAccount {
// MUST declare private fields here first
#balance;
#accountNumber;
constructor(initialBalance, accountNumber) {
// NOW we can initialize them
this.#balance = initialBalance;
this.#accountNumber = accountNumber;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(1000, "ACC123");
You cannot skip the declaration and jump straight to the constructor. This would fail:
class Invalid {
// Missing declarations!
constructor(value) {
this.#missing = value; // ERROR: Private field must be declared
}
}
Why This Rule Exists
JavaScript engines need to know upfront which private fields exist to allocate memory and ensure privacy. The declaration-before-use rule makes your class structure explicit and predictable.
Key Takeaway: Private fields must be declared at the class body level before you can initialize them in the constructor—declaration always comes first, initialization second.