Dates change after I push them onto a stack

I’m having trouble writing a script that creates new records (representing jobs) based on the following parameters:

  • start of date range
  • end of date range
  • days(s) included
    That is, if Mondays are included, create a job on each monday within date range.

I use a function to add jobs onto a stack, and call the function for each day of the week as required. My stack is defined outside the function as:

Let newJobs = ;

The new records created included a date field. That’s the problem. I can see my function looping through the dates correctly, and even pushing them onto the stack. But when everything is finish, every job on my stack has the final loop date. The same date. It was updated even after being added to the stack!

Function is:

function addJobs(opp,start, end, offset) {
    let jobDate = new Date;
    if (offset >= start.getDay()) {
        let addDays = offset-start.getDay(); 
        jobDate.setDate(start.getDate()+addDays);
    }
    else {
        let addDays = 7+offset-start.getDay();
        jobDate.setDate(start.getDate()+addDays);
    }
    for (let current = jobDate; current <= end; current.setDate(current.getDate()+7)) {        
        newJobs.push({
            "oppLink": opp,
            "newJobDate": current
        });
       )
    }
}

Greatful if anyone can point out where I’m going wrong please, and/or point me to a sample doing the same sort of thing.

It’s because date is mutable. You’re modifying the same object (current) and assigning it to each job. You’d need to clone the current date when adding it to newJobs.

for (let current = jobDate; current <= end; current.setDate(current.getDate()+7)) {        
    newJobs.push({
        "oppLink": opp,
        "newJobDate": new Date(current.getTime())
    });
}
1 Like

Thanks @LukaszWiktor. Mutable – an important concept to know.

This topic was solved and automatically closed 3 days after the last reply. New replies are no longer allowed.