0

try below code

let startDate = new Date(); const lastDate = new Date(); lastDate.setMonth(11,31); const timeArray = []; while(startDate <lastDate){ timeArray.push(startDate); console.log(startDate) startDate =new Date(startDate.setMonth(startDate.getMonth()+1)) } console.log('=================================='); console.log(timeArray)

But result shows as below

Thu Nov 03 2022 09:12:03 GMT+0530 (India Standard Time) Sat Dec 03 2022 09:12:03 GMT+0530 (India Standard Time) ================================== [ Sat Dec 03 2022 09:12:03 GMT+0530 (India Standard Time) Tue Jan 03 2023 09:12:03 GMT+0530 (India Standard Time) ] 

When I console the 'startDate' just after the array push it shows as expected , But when I console log the time array it has been shifted . Can someone explain this?

2
  • 1
    Well, you did call setMonth on the Date object. Perhaps you find it unexpected that it set the month of the Date object that you pushed into the array? Commented Nov 3, 2022 at 4:06
  • try logging after > startDate =new Date(startDate.setMonth(startDate.getMonth()+1)) You will get the point Commented Nov 3, 2022 at 4:10

1 Answer 1

2

I believe below is the code you were intending to write, where you clone the startDate and then modify the clone instead of modifying the original.

let startDate = new Date(); const lastDate = new Date(); lastDate.setMonth(11,31); const timeArray = []; while(startDate <lastDate){ timeArray.push(startDate); console.log(startDate) startDate = new Date(startDate); // uncouple it from the other date startDate.setMonth(startDate.getMonth()+1) } console.log('=================================='); console.log(timeArray)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.