Private Fields and Defaults
Private Fields and Defaults
π¨βπΌ Classes can hide implementation details using private fields and provide
flexibility with default parameter values.
Private Fields
JavaScript has native private fields using the
# prefix. These fields are
truly privateβthey can only be accessed inside the class:class Counter {
#count: number = 0 // Truly private - not accessible outside the class
increment() {
this.#count++
}
getValue() {
return this.#count
}
}
const counter = new Counter()
counter.increment()
counter.#count // β Error! Private field not accessible
Private fields enable encapsulationβhiding internal implementation details
from code outside the class. This prevents accidental modification and makes
your code more maintainable.
Default Parameter Values
Constructors can use default parameter values to make some parameters optional:
class Car {
make: string
model: string
year: number
constructor(make: string, model: string, year: number = 2024) {
this.make = make
this.model = model
this.year = year
}
}
const newCar = new Car('Toyota', 'Camry') // year defaults to 2024
const oldCar = new Car('Ford', 'Mustang', 1965) // year explicitly set
π¨ Open
and:
- Use
#prefix to create private fields - Use default parameter values in constructors
- Create classes that encapsulate their internal state
π° Use
# to declare a private fieldβit's truly private, not just a convention.π° Default parameters let you create flexible constructors with sensible defaults.


