Good beginner question 👍 — this one actually teaches a very important JavaScript concept.
You are pushing the SAME Date object reference into the array again and again.
👉 Date is an object, not a value type.
So when you do this:
MyDates.push(MyDate);
you’re not saving a new date — you’re saving a reference to the same object.
Later, when MyDate changes, all array entries point to that updated date, so they look identical.
Think of it like this 🧠
📌 You’re putting the same diary into the cupboard 4 times — not 4 different diaries.
Create one Date object → MyDate
Modify it in each loop (setDate)
Push same object into array each time
Result → array shows same final date everywhere ❌
You must create a new Date instance for each entry.
function Test_DateArray(){
let MyDate = new Date();
let MyDates = [];
for (let i = 1; i < 5; i++) {
MyDate.setDate(MyDate.getDate() + 1);
MyDates.push(new Date(MyDate)); // ✅ clone date
}
Logger.log(MyDates);
}
Avoid mutating the same date at all:
function Test_DateArray(){
let MyDates = [];
for (let i = 1; i < 5; i++) {
let d = new Date();
d.setDate(d.getDate() + i);
MyDates.push(d);
}
Logger.log(MyDates);
}
| Type | Behavior |
|---|---|
| Number / String | Copied by value |
| Object / Array / Date | Copied by reference |
So always remember:
Push objects by cloning, not reusing 🔁
--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/google-apps-script-community/984f5d5e-9d83-4d53-890f-0cf46d7e028fn%40googlegroups.com.