Array of Dates

7 views
Skip to first unread message

シモダフランジポータルサイト

unread,
5:11 AM (15 hours ago) 5:11 AM
to Google Apps Script Community
I'm afraid this beginner question will bore the reader, but allow me to ask about the next function, which outputs the array filled with the same dates.
Where is incorrect?
function Test_DateArray(){
  let MyDate = new Date();
  let MyDates = [];
  for(let i= 1; i < 5; i++){
    MyDate.setDate(MyDate.getDate() + 1);
    MyDates.push(MyDate);
    Logger.log(MyDates);
  }
}

DME

unread,
10:07 AM (10 hours ago) 10:07 AM
to google-apps-sc...@googlegroups.com

Good beginner question 👍 — this one actually teaches a very important JavaScript concept.

❌ What’s going wrong?

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.


🔍 Your code flow (simplified)

  1. Create one Date object → MyDate

  2. Modify it in each loop (setDate)

  3. Push same object into array each time

  4. Result → array shows same final date everywhere ❌


✅ Correct way: push a COPY of the Date

You must create a new Date instance for each entry.

✔️ Fix #1 (Recommended)

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);
}

✔️ Fix #2 (Cleaner approach)

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);
}

🧠 Key Concept (Very Important)

TypeBehavior
Number / StringCopied by value
Object / Array / DateCopied 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.


--
Reply all
Reply to author
Forward
0 new messages