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 create/export three classes:
User
- Public fields:
name,email,role(allstring) - Constructor
(name, email, role = 'user') - Omitting
rolemust leave it as'user'
BankAccount
- Public field:
accountNumber(string) - A private balance field (use
#so it is inaccessible outside the class) - New accounts start with balance
0 deposit(amount: number)increases the balance byamount(it accumulates)getBalance()returns the current balance
Config
- Public fields:
host(string),port(number),debug(boolean) - Constructor defaults:
host = 'localhost',port = 3000,debug = false new Config()must use all three defaults; custom args override them
Export all three:
export { User, BankAccount, Config }Fixtures and success criteria
const user = new User('Alice', 'alice@example.com')
const admin = new User('Bob', 'bob@example.com', 'admin')
const account = new BankAccount('12345')
account.deposit(100)
account.deposit(50)
const config = new Config()
const customConfig = new Config('example.com', 8080, true)
user.role === 'user'andadmin.role === 'admin'account.accountNumber === '12345'- A fresh account has
getBalance() === 0 - After the deposits above,
getBalance() === 150 - Default config:
host === 'localhost',port === 3000,debug === false - Custom config:
'example.com',8080,true
π° Use
# to declare a private fieldβit's truly private, not just a convention.π° Default parameters let you create flexible constructors with sensible defaults.


