0

I have an issue related to objects in javascript. I actually need to put the value of my original variable value in a temporary variable that I can refer later the perform a business logic.

The issue is that whenever I modify the original variable value the temporary gets updated too

Putting the value in the temporary variable

Here this.startingTime = 10:00

and this.endingTime = 12:00

this.startingTime = new Date(this.selectedAvailability.scheduleDate + ' ' + this.selectedAvailability.startTime);
this.endingTime = new Date(this.selectedAvailability.scheduleDate + ' ' + this.selectedAvailability.endTime);

this.tempStartTime = this.startingTime;
this.tempEndingTime = this.endingTime;

Updating as follow update the original and the temp

this.endingTime = 11:30

this.tempEndingTime = 11:30 (The temp variable gets updated also, but here what I want is the temp to stay 12:00)

this.endingTime.setMinutes(this.endingTime.getMinutes() - 30);
  • Does this answer your question? [Copy a variable's value into another](https://stackoverflow.com/questions/18829099/copy-a-variables-value-into-another) – francovici Jul 19 '20 at 17:29
  • 1
    The line `this.tempStartTime = this.startingTime;` doesn't create a copy of the date object, it just makes both `this.tempStartTime` and `this.startingTime` both refer to the same date object. Details in the [linked question](https://stackoverflow.com/questions/37817770/why-is-a-copy-of-my-variable-being-changed-unexpectedly)'s answers. If you want to copy a date, the best way is `= new Date(+original)` (in particular, **don't** just do `= new Date(original)`, it's not reliable cross-browser). – T.J. Crowder Jul 19 '20 at 17:38

2 Answers2

0

By doing this, you are giving the reference of your first variable to your temporary one, that's why they are updated together.

To prevent it, you should use something like object.assign or cloneDeep (this one is from lodash) to create a new reference.

Quentin Grisel
  • 4,794
  • 1
  • 10
  • 15
-1

this.tempStartTime = angular.copy(this.startingTime);

this.tempEndingTime = angular.copy(this.endingTime);

Try with this one