Sub topic 4
Immutable by Design
This chapter assumes you know modern JavaScript syntax, how const and let differ, and how the legacy Date setters such as setDate and setMonth work. The examples assume Temporal is available, either natively or through the polyfill set up in the earlier runtime-support chapter. Run them as ES modules, which use strict mode.
Every Temporal object is immutable: once you create a PlainDate, Instant, ZonedDateTime, or Duration, its value never changes. Methods that seem to modify a value return a new object instead. This one rule prevents a whole class of bugs that Date code is known for.
The Problem Immutability Solves
A Date is a mutable box around a timestamp. Any code holding a reference can change it, and every other holder of that reference sees the change.
const start = new Date(2024, 0, 31); // January 31, 2024 (months are 0-based)
const end = start; // copies the reference, not the value
end.setDate(end.getDate() + 7);
console.log(start.toDateString()); // 'Wed Feb 07 2024' (start changed too)
console.log(end.toDateString()); // 'Wed Feb 07 2024'The same thing happens when you pass a Date into a function that "just calculates" something but calls a setter along the way. To guard against it, Date code makes defensive copies with new Date(d.getTime()), and it is easy to forget one.
Here is the Temporal version of the same logic:
const start = Temporal.PlainDate.from('2024-01-31');
const end = start.add({ days: 7 });
console.log(start.toString()); // '2024-01-31' (unchanged)
console.log(end.toString()); // '2024-02-07'add cannot touch start. It computes a result and returns it as a new PlainDate.
How Derived Values Work
Every operation that produces a different value follows the same pattern: it reads the receiver, builds a new object, and leaves the receiver as it was.
The methods that return new values include:
| Method | Purpose | Example result type |
|---|---|---|
| `add`, `subtract` | Move by a duration | Same type as receiver |
| `with` | Replace specific fields | Same type as receiver |
| `round` | Round to a unit | Same type as receiver |
| `withTimeZone`, `withCalendar` | Change zone or calendar | `ZonedDateTime` / same type |
| `withPlainTime` | Replace the time part | `ZonedDateTime` or `PlainDateTime` |
| `negated`, `abs` (on `Duration`) | Flip or remove the sign | `Duration` |
with replaces the setter pattern from Date. Instead of d.setDate(1), you write d.with({ day: 1 }), and you can replace several fields at once:
const date = Temporal.PlainDate.from('2024-01-31');
const firstOfMonth = date.with({ day: 1 });
const febSameDay = date.with({ month: 2 }); // clamps to the last valid day
console.log(firstOfMonth.toString()); // '2024-01-01'
console.log(febSameDay.toString()); // '2024-02-29'
console.log(date.toString()); // '2024-01-31'Common Mistake: Discarding the Result
Date habits teach you to call a method for its side effect. With Temporal, calling add without using its return value does nothing useful:
let due = Temporal.PlainDate.from('2024-03-15');
due.add({ days: 10 }); // result thrown away
console.log(due.toString()); // '2024-03-15'
due = due.add({ days: 10 }); // reassign the variable instead
console.log(due.toString()); // '2024-03-25'The same rule applies in loops. You advance the loop variable by rebinding it:
const first = Temporal.PlainDate.from('2024-02-27');
const last = Temporal.PlainDate.from('2024-03-02');
const days = [];
for (let d = first; Temporal.PlainDate.compare(d, last) <= 0; d = d.add({ days: 1 })) {
days.push(d.toString());
}
console.log(days);
// ['2024-02-27', '2024-02-28', '2024-02-29', '2024-03-01', '2024-03-02']What Happens If You Try to Assign a Field
Fields such as year, month, and day are getters defined on the prototype, with no setters. In strict mode, which includes ES modules and class bodies, assigning to one throws:
const date = Temporal.PlainDate.from('2024-03-15');
try {
date.year = 2025;
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(date.year); // 2024In a sloppy-mode classic script, the assignment fails silently and date.year stays 2024. Either way, the value does not change.
Benefits in Practice
Immutability gives you guarantees you can rely on:
- Safe sharing. You can export a constant such as
const EPOCH_START = Temporal.PlainDate.from('2000-01-01'), pass it anywhere, and use it as a default parameter without defensive copies. - Predictable functions. A function that receives a
ZonedDateTimecannot change the caller's value, so you only need to look at return values when reasoning about it. - Safe caching. A computed value, such as a list of holidays, can be stored and handed out repeatedly with no risk of corruption.
- Easier state management. Frameworks that detect changes by reference, such as React state or Redux, work naturally. A new date means a new object.
Edge Case: Identity Versus Value
Because each operation produces a new object, two Temporal values with the same content are usually different objects. === compares identity, so use equals to compare values:
const a = Temporal.PlainDate.from('2024-03-15');
const b = Temporal.PlainDate.from('2024-03-15');
console.log(a === b); // false
console.log(a.equals(b)); // trueThis affects Map and Set, which also compare by identity. To key a collection by date, use the string form:
const bookings = new Map();
bookings.set(a.toString(), 'Room 4');
console.log(bookings.get(b.toString())); // 'Room 4'
console.log(bookings.has(b)); // false (b is not the key)toString() works as a key for one type at a time. Don't mix types, such as PlainDate and PlainDateTime, or different calendars in the same map unless their strings are unambiguous for your use case.
Exercise
What does this code print, and why? const d = Temporal.PlainDate.from('2024-12-31'); d.add({ days: 1 }); const e = d.with({ month: 6 }); console.log(d.toString(), e.toString());
Show answer
It prints 2024-12-31 2024-06-30. The result of add is discarded, so d stays December 31. with({ month: 6 }) builds a new date from d's year and day, and June has only 30 days, so the default constrain overflow clamps the day to 30.
Exercise
A teammate writes function nextWeek(date) { date.add({ weeks: 1 }); return date; } and says the tests show it returns the original date. Fix the function, and explain why it can't accidentally change the caller's date.
Show answer
Return the result: function nextWeek(date) { return date.add({ weeks: 1 }); }. The original version returned its unchanged argument because add never modifies its receiver. Temporal objects are immutable, so no code inside the function can change the caller's value.
Exercise
You store Temporal.PlainDate objects in a Set to track visited dates, but set.has(Temporal.PlainDate.from('2024-03-15')) returns false after you added the same date. What is wrong, and how do you fix it?
Show answer
Set compares objects by identity, and from creates a new object every time, so the two dates are different objects with equal values. Store and look up date.toString() instead, for example set.add(date.toString()) and set.has(other.toString()).