0

so I 'm having a strange bug here related to changing the month of a date object. here is the code.

let date = new Date();
let captions = [];

for (let i=0; i < 12; i++) {
  let newDate = date;
  newDate.setMonth(date.getMonth() - i);
  let month = newDate.toLocaleString('default', { month: 'short' });
  let year = newDate.getFullYear();

  captions.push({month, year});
}

The thing is value of date variable is changing every loop. I can understand why.

Anyone?

DougMoraes
  • 11
  • 4

1 Answers1

0

Your issue is with this assignment: let newDate = date;

What happens is that now newDate is a reference to your original date variable.

As Lennholm suggested in his comment below:

"it's not a reference to the original variable but to the same object (in memory) that the original variable also references. The two variables are independent of each other."

To avoid that change it to this: let newDate = new Date(date);

Check this stackblitz.

robert
  • 5,742
  • 7
  • 28
  • 37
  • *"newDate is a reference to your original date variable"* – This is a bit misleading, it's not a reference to the original variable but to the same object (in memory) that the original variable also references. The two variables are independent of each other. – Lennholm Mar 28 '20 at 18:53
  • Thank you @Lennholm. I updated my answer. – robert Mar 28 '20 at 19:09
  • Thank you for your answer! This made totally sense! – DougMoraes Mar 29 '20 at 16:45