Surprising outcomes when working with JavaScript date and time functionalities

Check out the code snippet below:

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)

However, the resulting output displays:

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)
]

After pushing 'startDate' into the array and checking it immediately, it appears as expected. However, when logging the time array itself, the dates seem to have shifted. Can anyone provide an explanation for this behavior?

Answer №1

It appears that the code snippet below is what you intended to write. In this script, you are cloning the startDate and then making modifications to the cloned date rather than altering 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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The integration of Raphaeljs library with SmartPhones opens up a world of

I recently incorporated the incredible JavaScript library, RaphaelJS, into my website to create maps, animations, and interactive features. Interestingly, I have observed that the scripts utilizing this library function seamlessly on iPhones but encounter ...

Sending a variable to a template in AngularJS

I am looking for a way to pass a variable or text to a template in order to display the value within my template. While browsing through resources, I found an example on jsFiddle that demonstrates this functionality using ng-repeat. However, I am curious ...

Prevent drag and drop functionality in QtWebkit

As I work on creating an HTML GUI for my application using Qt's WebKit, everything is going smoothly with one minor issue. I am trying to prevent users from dragging and dropping images from the GUI itself. While I have successfully disabled text sele ...

Switching measurement unit to jQuery when retrieving image weight

After coming across a solution on this question, I am looking to determine the weight of an image from a file input. The solution I found displays the result in MiB (Mebibyte) unit. Is there a way to show the image weight using the same code, but in a diff ...

Switch the jQuery overlay image upon clicking a button

Is there a way to dynamically change the overlay image of a jQuery-ui dialog using a button click from inside the dialog? I attempted to do so in the code snippet below, but unfortunately, the overlay image does not update. It seems that I need to manipu ...

Change every occurrence of span class red to be a strike tag

I'm attempting to replace all span tags with the red class and their content with a strike tag. However, I've encountered an issue where it doesn't seem to be replacing the specific span tags as expected. Below is the code snippet: let s ...

Adding the node_modules directory to a global npm package: A step-by-step guide

I've developed an npm package with numerous dependencies. However, when I test my app using npm install -g ./, the application is added to the global npm directory without the node-modules folder. As a result, when the app is launched from the termina ...

ng-Mask: Enhancing String Operations

My goal is to only allow the input of uppercase characters as defined by the Mask. For example, using the mask code 'A' with regex [A-Z]. <input type="text" class="form-control" mask="AAAA"> I expect only uppercase characters in the range ...

Combining Laravel and vue.js for seamless file uploading functionality

Successfully uploading files using vue.js 1.0 with a POST request looks like: store () { this.storingMessage = true; var form = new FormData(); form.append('subject', this.message.subject); form.ap ...

Surprising results when using react-router-dom alongside React's Context API

I am currently working on a small project where I am trying to implement basic authentication using the React Context API without Redux. Here is the code snippet: import { createContext, useContext, useState } from 'react' export const AuthConte ...

Looking to maintain the value of a toggle button in a specific state depending on certain condition checks

I have a situation where I need to keep a toggle button set to "off" if my collection object is empty. Previously, I was using v-model to update the value of the toggle button. However, now I am attempting to use :value and input events, but I am strugglin ...

What is the reason behind the effectiveness of this prime number verifier?

Take a look at this code snippet that effectively checks whether a number is prime: var num = parseInt(prompt("Enter a number:")); var result = "Prime"; for (var i = 2; i < num; i++) { if (num % i === 0) { result = "Not Prime"; break; } } ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

Potential unhandled promise error in react-native

When I use the code below, it produces a "Possible unhandled promise rejection" error: constructor(props){ super(props) DatabaseHandler.getInstance().getItems(function (items) { console.log(items)//successfully print data ...

Leveraging jQuery to establish headers in an ajax request

I want to integrate an Office 365 Rest API into my application. When I test the URL within the same browser session, I can view some XML data. https://i.sstatic.net/1lbZZ.png However, when I try pasting the URL into an incognito window, I encounter this ...

What is the most effective method for combining data from two APIs into a single React table?

Looking to combine data from 2 separate APIs that both have pagination capabilities. What is the most efficient method to present the merged data in a table? The data needs to be joined based on their unique id, however one API provides fewer records tha ...

The path-to-regexp in vue-router fails to match an optional group of route path parameters

Exploring Vue.js Router Currently, I am delving into the official vue-router of vue.js. My focus is on implementing route matching using dynamic route matching. With vue-router utilizing path-to-regexp underneath its operations, regex can be employed in ...

Executing a JavaScript function on an HTML page within an embedded object tag

I am facing a scenario where I have a page with another page embedded using an object tag. The challenge is to call a JavaScript function from the "parent" page, specifically reaching a function within the embedded code. In the past, my solution involved ...

Using RegEXP in Javascript, you can easily eliminate characters that fall between two special characters without removing the special characters

I'm facing an issue with a string that looks like this: var str = "1111 type reallycoolsentence\text.json\n1111 type anotherreallycoolsentence text2.json My goal is to eliminate the characters located between the backslashes in the str ...

Comparing strings with if-else statement

I am having trouble comparing strings in this array. For some reason, the strings are never equal. var person = ["Sam", "John", "Mary", "Liz"]; var searchedName = prompt("Enter name"); var resultMessage = ""; for (index in person) { var currentName = ...