Why javascript date.setDate() change the value of other date variables
date, html, javascript, jquery, variable-assignment
Solution
You need to make a copy of your dates, like this:
date3 = new Date(date1.getTime());
date2 = new Date(date1.getTime());
or simply:
date3 = new Date(date1);
date2 = new Date(date1);
instead of
date3 = date1;
date2 = date1;
Otherwise, your variables all point to the same Date object (initially referenced by `date1`).
EDIT (about memory allocation)
- Example 1:
var date1 = new Date(); // Memory allocation for an object
var date2 = new Date(1991,4,11); // Memory allocation n°2
var date3; // Obviously no memory allocation here
date3 = date1; // No memory allocation either, date2 and date3
date2 = date1; // become references of the object in date1
In this example, there are two memory allocations but only one of them is useful as the object in date2 is not used.
Note: The object that was originally in date2 still exists, but is not referenced anymore (it will be garbage-collected).
- Example 2:
var date1 = new Date(); // Memory allocation for an object
var date2 = new Date(date1); // Memory allocation n°2
var date3 = new Date(date1); // Memory allocation n°3
In this example, there are three memory allocations for 3 different objects. The 2nd and 3rd allocations consist in creating new Date objects, containing a copy of the object in date1.
I hope it is clearer with this little explanation. If you're interested in memory management in JavaScript, I suggest you have a look at this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
Problem
When i'm trying to know functionality of setDate() ,setTime() of javscript date i came across this problem. ``` <script> var date1 = new Date(); var date2 = new Date(1991,4,11); var date3 = new Date(1992,4,11); date3 = date1; date2 = date1; date2.setDate(date2 .getDate() + 40);//im changing only date2 value using setDate() //print values </script> ``` I think the result will be like: Fri Jul 04 2014 Wed Aug 13 2014 Fri Jul 04 2014 But in output all date variables have same value: Wed Aug 13 2014 Wed Aug 13 2014 Wed Aug 13 2014 jsfiddle If i do similar kind of code with integer variables they work like as i think(all int variables have different values). Summary of Questions - How date assignment and number assignment differs? - Why and how javascript setDate() tracking other date variables? - Last but not least What i have to do if i want to change only date2 value with these assignments? Thanks in Advance.