Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Date object being changed [duplicate]

I have a situation when I set expire to a date object. After altering 'expire' the 'object.created' is changed when it should not be. Why is 'object.created' be changed? Thanks!

let expire = object.created; // object.created: Wed Mar 02 2016
expire.setDate(12);

console.log(expire); // Wed Mar 12 2016
console.log(object.created); //Wed Mar 12 2016 <-- WHY?!
like image 465
emarel Avatar asked Dec 17 '25 14:12

emarel


1 Answers

Assigning a reference to an object from one place to another does not involve making a copy. If you want a complete copy of the date:

let expire = new Date(object.created);

If you don't do that, there's only one Date instance involved; both expire and object.created refer to the same object in your code.

like image 138
Pointy Avatar answered Dec 19 '25 06:12

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!