1

I want to pass a date to a javascript function for some manipulation. The problem I am facing here is: the function is changing the actual date parameter though it works on a local parameter. Here is an example where I have mentioned my issue

var myDate = new Date();
console.log(myDate);//Result is Mon Oct 22 2018 09:40:01
function manipulate(d){
    d.setDate(d.getDate()+1);
    console.log(d);//Result is Oct 23 2018 09:40:01
    return d;
}
var result = manipulate(myDate);
console.log(result);//Result is Oct 23 2018 09:40:01 as expected.
console.log(myDate);//Result is Oct 23 2018 09:40:01. I want this to be my initial value. That is Mon Oct 22 2018 09:40:01

I guess it JS uses pass by reference if the date is used as a parameter. How can I resolve the above-mentioned issue?

Regards,

SAP Learner

Noor A Shuvo
  • 2,639
  • 3
  • 23
  • 48
SAP Learner
  • 61
  • 4
  • 17
  • 1
    Try to take a copy of date in the function as follows: var dLocalCopyFrom = new Date(d.getTime()); dLocalCopyFrom.setDate(dLocalCopyFrom.getDate()+1); This will not alter the actual date – F H Oct 22 '18 at 09:15
  • Use the Date object's getTime() function to get a clone. https://stackoverflow.com/questions/1090815/how-to-clone-a-date-object-in-javascript – Ryan Pierce Williams Oct 22 '18 at 09:16

1 Answers1

2

You have to copy it first

function manipulate(d){
    var s = new Date(d)
    s.setDate(s.getDate()+1);
    console.log(s);//Result is Oct 23 2018 09:40:01
    return s;
}
ZeroCho
  • 1,358
  • 10
  • 23