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
index.ts
and create/export three classes:

User

  • Public fields: name, email, role (all string)
  • Constructor (name, email, role = 'user')
  • Omitting role must 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 by amount (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' and admin.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.

Please set the playground first

Loading "Private Fields and Defaults"
Loading "Private Fields and Defaults"
Login to get access to the exclusive discord channel.
Loading Discord Posts