1

I know, title isn't probably clear, but I have this code:

var date1=new Date();
alert(date1);
var date2=date1;
alert(date2);
date2.setMonth(date1.getMonth() + 6);
alert(date1+" - "+date2);

Why date1 change? I think date1 should remain the current date and date2 six months later ...

Thanks

Francesco G.
  • 679
  • 3
  • 13
  • 32

3 Answers3

5

Dates are objects in JavaScript. When you set date2=date1, both date1 and date2 will reference the same object. Since they are both references to the same date object, the object may be updated or inspected using either.

qubyte
  • 17,558
  • 3
  • 30
  • 32
1

Both the variables are pointing to same date object. You can do this instead

var date1=new Date();
alert(date1);
var date2=new Date(date1.valueOf());
alert(date2);
date2.setMonth(date1.getMonth() + 6);
alert(date1+" - "+date2);

In this approach, I am creating new object using values of existing one. Now there are two objects being point by different variables.

While you had assigned same object to both variables.

Panther
  • 3,312
  • 9
  • 27
  • 50
  • The Date can be copied as `var date2=new Date(date1)`. To accommodate ancient IE and dates from year 0 to 99, use `var date2=new Date(+date1)` (which still works everywhere, even in not old IE). ;-) – RobG Mar 28 '17 at 12:26
0

Because date2 gets the reference to date1, not value.

SaXXuM
  • 946
  • 1
  • 5
  • 7