0

I have a for loop in javascript which concats data in calendarEvents:

drop(info) {
    var that = this;
    var startDate = info.date;
    var frequency = this.skippingNumber;

    for (var i = 0; i <= 3; i++) {
      (function (start) {
        that.calendarEvents = that.calendarEvents.concat({
          title: 'Dropped Event',
          start: start,
          allDay: info.allDay
        });
      })(startDate);
      startDate = this.addDays(startDate, frequency);
    }
  }

addDays(date: Date, days: number): Date {
    var passedDate = date;
    passedDate.setDate(passedDate.getDate() + days);
    return passedDate;
  }

If I log startDate inside the loop , I get actual values i.e, Monday, Tuesday, Wednesday, Thursday. But when I log calendarEvents, all I get is Thursday in every data. Can anyone help me with this? Thanks in advance !!

Alator
  • 497
  • 6
  • 23
Dot Net developer
  • 436
  • 1
  • 5
  • 19
  • 1
    Your `startDate` is the same object and you're passing a reference to it every time. – zerkms May 21 '19 at 10:26
  • All invocations of `addDays()` receive as argument, modify and return the same object (`var startDate = info.date`). – axiac May 21 '19 at 10:26
  • Have a look [here](https://www.reddit.com/r/javascript/comments/a50jte/is_it_best_to_use_var_or_let_in_for_loop/) – Claudio Busatto May 21 '19 at 10:36

2 Answers2

3

All invocations of addDays() receive as argument, modify and return the same object (var startDate = info.date).

Rewrite the addDays() method to create and return a new Date object:

addDays(date: Date, days: number): Date {
    var passedDate = new Date(date.getTime());
    passedDate.setDate(passedDate.getDate() + days);
    return passedDate;
}
axiac
  • 68,258
  • 9
  • 99
  • 134
0

You only have one startdate object that you're mutating as the loop runs. When it finishes, you have an array that contains references to the same object.

One fix would be to clone your startdate object before you concat it into the array:

(function (start) {
    that.calendarEvents = that.calendarEvents.concat({
      title: 'Dropped Event',
      start: new Date(start.getTime()),
      allDay: info.allDay
    });
  })(startDate);

Though as suggested it would be better to re-write your addDays function so that it doesn't mutate the date object you pass in. Where possible, functions should not mutate their inputs.

Will Jenkins
  • 9,507
  • 1
  • 27
  • 46