Home > database >  JavaScript in function Date var argument changes for no reason?
JavaScript in function Date var argument changes for no reason?

Time:11-21

Noob here. Sorry if the question is stupid. I'm writing a script for travel purpose. I need to get dates of departure start and end given the day of the week. And dates for returns given the offset of start/end date; After calling function departure start date is also changing. I can't comprehend my error. Please help.



var departstart=getNextDayOfTheWeek(3,0);
console.log("Departure from "   departstart);
var departend=getNextDayOfTheWeek(3,0);
console.log("Departure to "   departend);
var returnstart=getoffday(3,departstart);
// check again depature
console.log("Departure from "   departstart);
// Has changed?!?!?!
console.log("Return from "   returnstart);
var returnend=getoffday(3,departstart);
console.log("Return to "   returnend);

// Gets a date of next day of the week
function getNextDayOfTheWeek(dayOfWeek, excludeToday = true, refDate = new Date()) {

    refDate.setHours(0,0,0,0);
    refDate.setDate(refDate.getDate()    !!excludeToday  
                    (dayOfWeek   7 - refDate.getDay() -  !!excludeToday) % 7);
    return (refDate);

}

// Gets a date of diff day from given date
function getoffday(diff=0, workyday = new Date()) {
console.log("Inside function before execution "   workyday);
workyday.setHours(0,0,0,0);
workyday.setDate(workyday.getDate()   diff);
console.log("Inside function after execution "   workyday);
return (workyday);
}

I've thought may be I should not use argument in function and define local var, but that did not help.

CodePudding user response:

If you don't want to modify a certain date all the time (as it is right now), you could e.g. modify your getoffday function as follows:

// Gets a date of diff day from given date
function getoffday(diff=0, workyday = new Date()) {
    // we create a new Date object with the value of the provided "workyday" param
    // now we modify only this copied date - the provided date does not change
    const dateCopy = new Date(workyday.getTime());
    console.log("Inside function before execution "   dateCopy);
    dateCopy.setHours(0,0,0,0);
    dateCopy.setDate(dateCopy.getDate()   diff);
    console.log("Inside function after execution "   dateCopy);
    return (dateCopy);
}

Of course, you could use the same method for your getNextDayOfTheWeek function. This way you get isolated results (no influence of variable values outside your function).

  • Related