Search code examples
javascriptarraysangularmomentjspass-by-rvalue-reference

Array Push 'Different Info' Results in Pushing Same First Iteration For Every Iteration


I am trying to notify user about his medication 3 times daily So I created:

let timesPerDay = []

const today = moment();
//not working
for (let i = 0; i < 3; i++) {
  timesPerDay.push(today.add(8 * i, "hour"));
}
//working normally
for (let i = 0; i < 3; i++) {
  console.log(today.add(8 * i, "hour"));
}

console.log(timesPerDay)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

But there is a weird bug that when pushing to array it saves the first date for every iteration not adding 8 hours to it every time, that's so weird!

How Array.push is working?

Is JavaScript too fast in creating the array so the first loop is not working but the second is working?

CodePen: https://codepen.io/microsmsm-the-flexboxer/pen/BaypYVO

Edit:

Same Snipped I am using after answers is not working

https://codepen.io/microsmsm-the-flexboxer/pen/KKwaoeM

enter image description here

enter image description here


Solution

  • walking you through your code step by step:

    let timesPerDay = [] // create an array
    
    const today = moment(); // create a moment object
    
    for (let i = 0; i < 3; i++) {
      // add hours to moment object
      // push a reference to that moment object into your array
      // it's always a reference to the SAME moment object, so the same object is referenced in your array multiple times
      // mutations to that object will show everywhere it is referenced
      timesPerDay.push(today.add(8 * i, "hour")); 
    }
    
    for (let i = 0; i < 3; i++) {
      // add hours to same moment object
      // log the string representation of that object AT EACH ITERATION
      // once transformed to a string, the string representation will not change as it is no longer part of the object
      console.log(today.add(8 * i, "hour"));
    }
    
    console.log(timesPerDay) // log string representation of your array, which is just 3 references to the same object