0

Can you help me to understand why d1 has different value in each alert() ? Thanks.

<script>
d1 = new Date("01/01/2015");
d2 = d1;
alert(d1);
d2.setDate(d2.getDate()+10);
alert(d1);
</script>
MarcioAB
  • 601
  • 1
  • 5
  • 11

1 Answers1

0

Because objects are reference types, and in the line d2 = d1 a pointer is passed to d2 that points to d1 and if you d2.setDate(d2.getDate()+10); execute this line is same as you edited d1.setDate(d1.getDate()+10);

IamK
  • 2,753
  • 5
  • 30
  • 39
  • Well, the value of the variable *d1* is a reference and `d2 = d1` copies the reference and assigns it to *d2* so that both variables reference the same Date object. – RobG Oct 12 '15 at 01:01
  • Thank you. So, as Date is an object and just copy the pointer. So, I need to create a new object and copy it like this – MarcioAB Oct 12 '15 at 03:32