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:
  1. Use # prefix to create private fields
  2. Use default parameter values in constructors
  3. 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.

Please set the playground first

Loading "Private Fields and Defaults"
Loading "Private Fields and Defaults"