Array of Dates

25 views
Skip to first unread message

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

unread,
Dec 18, 2025, 5:11:44 AM (6 days ago)  Dec 18
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,
Dec 18, 2025, 10:07:15 AM (6 days ago)  Dec 18
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 referenceinto 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 diaryinto 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 objectinto 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 instancefor 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)

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 .


--
Reply all
Reply to author
Forward
0 new messages