Emmanuel Akinfulubi

JavaScriptDate

Copy a date object in JavaScript

Intermediate · 4 min read

Before you change a date, you usually want a copy of it. A booking form might keep the check-in date and work out the check-out date from it. If the code changes the check-in date by accident, the form shows the wrong stay. Copying first keeps the original safe.

In this tutorial you will see why const b = a does not copy a date, and learn two ways that do. You will also see how to tell whether two dates hold the same moment, because === gives a surprising answer. You need to know how to make a date with new Date(year, month, day) and that setDate changes the day of the month.

A variable holds a reference, not the date

A date is an object. When you put an object in a variable, the variable doesn't hold the object itself. It holds a reference: a pointer that says where the object lives in memory.

Copying the variable copies the pointer. Now two names point at one object:

JavaScript

const a = new Date(2026, 0, 15);
const b = a;
console.log(a === b); // true: one object, two names

Numbers and strings don't behave this way, because they can't be changed. A date can: every set method changes the object in place. So if two names share one date, a change through either name shows up in both.

How to make a real copy

To copy a date, build a new one for the same moment. new Date accepts another date, so new Date(a) does it. So does new Date(a.getTime()), which passes the date's timestamp: the number of milliseconds since 1 January 1970 in UTC.

Here is the exercise. Try it on your own first if you like, then read on and we will build it together.

21 Copy a date before you change it

fair

Show that assigning a date to another variable does not copy it, and show two ways that do.

Stuck? Three hints, smallest first
  1. 1. const b = a gives two names for one object.
  2. 2. new Date(a) and new Date(a.getTime()) both build a new one.
  3. 3. Two dates for the same instant are equal by timestamp and not by ===.

Step 1: watch a shared date move

Start with the version that looks like a copy but isn't:

Step 1

const shared = new Date(2026, 0, 15);
const alias = shared;
alias.setDate(20);
console.log(shared.getDate()); // 20
console.log(alias === shared); // true

You only changed alias, yet shared moved to the 20th as well. alias is just a second name for the same date. This is the bug a real copy prevents.

Step 2: copy with new Date(date)

Now build a separate date and change that instead:

Step 2

const start = new Date(2026, 0, 15);
const copy = new Date(start);
copy.setDate(20);
console.log(copy.getDate());  // 20
console.log(start.getDate()); // 15
console.log(copy === start);  // false

new Date(start) reads the moment stored in start and makes a brand new date for it. Changing copy leaves start on the 15th. copy === start is false because they are two different objects.

Step 3: copy through the timestamp

The second way spells out what the first one does:

Step 3

const viaTimestamp = new Date(start.getTime());
console.log(viaTimestamp.getTime() === start.getTime()); // true
console.log(viaTimestamp === start);                     // false

start.getTime() is a plain number. A number can't be shared the way an object can, so the new date is fully separate. Both ways give the same result. new Date(start) is shorter, and new Date(start.getTime()) makes the intent very clear to someone reading the code.

Step 4: two copies, same moment, not ===

Make a copy and leave it alone. It holds exactly the same moment as the original:

Step 4

const twin = new Date(start);
console.log(twin.getTime() === start.getTime()); // true
console.log(twin === start);                     // false

=== on two objects asks "are these the same object?", not "do they hold the same value?". So two dates for the same moment are never === unless they are literally one object. To compare the moments, compare getTime().

There is one more way to see that they match. JSON.stringify turns a date into its ISO text, so two separate dates for the same moment turn into the same string:

JavaScript

console.log(JSON.stringify(twin) === JSON.stringify(start)); // true

Step 5: copy inside your helpers

The habit pays off when you write a function that changes a date. Copy first, change the copy, return the copy:

Step 5

function addDays(date, days) {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}
const monday = new Date(2026, 0, 12);
const friday = addDays(monday, 4);
console.log(monday.getDate(), friday.getDate()); // 12 16

The caller's monday is still the 12th. Without the copy, monday would have become the 16th as soon as the function ran.

The full solution

The panel builds a real copy and a shared alias, changes both, and checks which originals moved. It also compares an untouched copy by timestamp and with ===. Press Run to see the results.

The answer

// A real copy. Mutating it leaves the source alone.
const start = new Date(2026, 0, 15);
const copy = new Date(start);
copy.setDate(20);

// Not a copy: one object with two names.
const shared = new Date(2026, 0, 15);
const alias = shared;
alias.setDate(20);          // this moves `shared` as well

const viaTimestamp = new Date(start.getTime());
const twin = new Date(start);   // built and left alone

console.log('start :', start.toDateString(), '<- untouched');
console.log('copy  :', copy.toDateString());
console.log('shared:', shared.toDateString(), '<- moved by the alias');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the copy moved', copy.getDate(), 20);
test('the source did not', start.getDate(), 15);
test('the alias moved the object it shares', shared.getDate(), 20);
test('because the alias IS the same object', alias === shared, true);
test('while the copy is a different object', copy === start, false);
test('an untouched copy holds the same instant', twin.getTime(), start.getTime());
test('but it is still not === to it', twin === start, false);
test('a timestamp round-trip copies just as well', viaTimestamp.getTime(), start.getTime());
test('JSON comparison sees them as equal, which is why same() says true', same(twin, start), true);

Date is mutable, so passing one into a function is passing a handle to something the function can change under you. Every helper in the rest of this section therefore starts with const copy = new Date(date) and returns the copy. It is one line and it removes a whole category of bug.

The last two assertions are worth holding together: twin === start is false while same(twin, start) is true. The helper compares JSON.stringify output, and JSON.stringify puts a date through toISOString, so two distinct objects for the same instant serialise identically. Equality for dates is a question about instants, not about objects.

Common mistakes

  • Writing const copy = date. That copies the reference, not the date. Any set call on copy changes the original too.
  • Copying with { ...date } or Object.assign({}, date). These make a plain object with none of the date's methods, so copy.getDate() throws. Use new Date(date).
  • Checking a copy with ===. A real copy is never === to the original. Compare copy.getTime() === date.getTime() instead.

Try it yourself

  1. Write addHours(date, hours) that copies the date, moves the copy on with setHours, and leaves the input unchanged.
  2. Make two dates for the same moment and print a.getTime() === b.getTime() and a === b. Then set b = a and print both again.
  3. Write sameMoment(a, b) that returns true when two dates hold the same timestamp.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.