Arrays containing references to Javascript objects

Recently, I've observed some odd behavior with one of my arrays. It seems that the issue lies in how Javascript stores object references within arrays. To illustrate this problem, I'll share a code snippet that I previously posted as an answer on SO. The code simply loops through to retrieve today's date and the 6 previous dates of the month.

var dates = [];
var date = new Date();

for (var i = 0; i < 7; i++){
  var tempDate = new Date();
  tempDate.setDate(date.getDate()-i);
  dates.push(tempDate);  
}
console.log(dates);

Output:

[Thu Jun 05 2014 14:54:14 GMT+0100 (GMT Daylight Time), 
Wed Jun 04 2014 14:54:14 GMT+0100 (GMT Daylight Time), 
Tue Jun 03 2014 14:54:14 GMT+0100 (GMT Daylight Time), 
Mon Jun 02 2014 14:54:14 GMT+0100 (GMT Daylight Time), 
Sun Jun 01 2014 14:54:14 GMT+0100 (GMT Daylight Time), 
Sat May 31 2014 14:54:14 GMT+0100 (GMT Daylight Time), 
Fri May 30 2014 14:54:14 GMT+0100 (GMT Daylight Time)]

This is correct, and should be expected since tempDate is constantly re-created as a new Date object inside the loop.

However, when I move tempDate out of the loop, it appears to update all objects in the array each time the loop iterates (and the loop unexpectedly goes one Month and 1 day too far back to April 29th):

var dates = [];
var date = new Date();
var tempDate = new Date();

for (var i = 0; i < 7; i++){
  tempDate.setDate(date.getDate()-i);
  dates.push(tempDate);  
}
console.log(dates);

Output:

[Tue Apr 29 2014 14:52:21 GMT+0100 (GMT Daylight Time), 
Tue Apr 29 2014 14:52:21 GMT+0100 (GMT Daylight Time), 
Tue Apr 29 2014 14:52:21 GMT+0100 (GMT Daylight Time), 
Tue Apr 29 2014 14:52:21 GMT+0100 (GMT Daylight Time), 
Tue Apr 29 2014 14:52:21 GMT+0100 (GMT Daylight Time), 
Tue Apr 29 2014 14:52:21 GMT+0100 (GMT Daylight Time), 
Tue Apr 29 2014 14:52:21 GMT+0100 (GMT Daylight Time)]

My two questions are:

  1. Why does the object stored in the array mutate with each iteration? (I suspect this could be due to Javascript storing references to the object, but an explanation would be appreciated)
  2. Why does the second code snippet run one iteration too far? In the first example, the loop successfully ends after 7 iterations on May 30th (7 days ago), whereas in the second example, the resulting date after the iterations falls back to April 29th - over a month in the past. Why?

Edit: I have provided a basic jsfiddle for testing the code.

Answer №1

Creating a new object with <code>var tempDate = new Date();
. This means that in the example below:

var array = [tempDate,tempDate,tempDate,tempDate,tempDate];

array[0] is actually the same object as array[1]

This concept applies to objects in almost all programming languages, as shown in the code snippet:

var a = tempDate;
var b = tempDate;
var c = b;

In the above example, a, b, c, and tempDate refer to the same object.


Regarding question 2:

Please take a look at this fiddle: http://jsfiddle.net/Mqnmm/

When a new object tempDate is always set to today's date, then you can use setDate() to adjust it.

However, when using an old object, the date is initially set to Sat, 31 May 2014 14:23:34 GMT, and by applying tempDate.setDate(-1), it sets the date to the last N days of the previous month

For more information on subtracting days from a date in JavaScript, check out Rob Dawley's answer here: Subtract days from a date in JavaScript

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

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

Encountering an error when importing chart.js-plugins-annotations

import { annotation, Chart, defaults } from 'chart.js'; An issue arises when using this import statement: localhost/:1 Uncaught TypeError: Failed to resolve module specifier "chart.js". Relative references must start with either &quo ...

Switching the body's background image dynamically using javascript

I'm attempting to switch up the background image using JavaScript. Here's how I've defined the background: body { background: black; overflow-x: hidden; overflow-y: hidden; } body:before { overflow-x: hidden; overflow ...

Guide on creating an autonomous select-all checkbox to show table columns

How can I create checkboxes with a "Select all" option and the following functionality: Check one or more checkboxes to show specific table columns. Uncheck them to hide the columns (toggle). Select the "Select all" checkbox to display all table columns. ...

Extracting information from within Ajax's Jsonp

How can I retrieve data from the Ajax function(result)? Why isn't this app working? Please assist me. function star(a) { var res; $.ajax({ url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35 ...

Retrieving information from Firebase after updating it

My goal is to automatically navigate to a specific ID after adding an item to my realtime database. Despite following the documentation's proposed solution, I am encountering issues with its implementation. Following the use of the push().set() meth ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

"Enhancing Webpages with AngularJS: The Power of Binding and Re

Using AngularJS to load AJAX content and ng-repeat to generate a list of items. I have a placeholder {{noun}} in the content, expecting it to be replaced with data from $scope.noun when the AJAX content is loaded. However, this does not happen automaticall ...

How can I send and retrieve multiple variables in a URL using WordPress?

There seems to be an issue where I can only retrieve the first variable, specifically "product_category," from the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon. When I output JavaScript to confirm that the variables are set, ...

Is it possible for a binary tree to be generated from an unsorted array by constructing a max heap?

Imagine having a disordered array containing 10 items int[] arr={∞,1,2,3,4,5,6,7,8,9,10}; If I run the following code public void build_heap(){ for(int i=size/2;i>=1;i--) max_heapify(i); } Under what conditions wil ...

To ensure the next line only runs after the line above has finished executing, remember that the function is invoked in HTML

my.component.html <button (click)="refresh()">Refresh</button> my.component.ts refresh() { let self = this; self.isRefresh = true; //1st time self.getfun().then(() => { self.isRefresh = false; ...

What is the most efficient method for comparing two multidimensional arrays and incrementing a variable when matching values are identified?

In my current setup, I have a shopping cart that utilizes two arrays: one for storing the cart products in session and another to display these products. I am looking for a way to extract the count value from the cart array and associate it with the corres ...

Image of sprite is not displayed

Having trouble displaying a sprite. Here is the HTML file : <head> <script src="https://github.com/photonstorm/phaser-ce/releases/download/v2.7.5/phaser.min.js"></script> </head> <body> <div id="game"></div& ...

Managing data flow in React and Reflux: Utilizing a single component duplicated in the DOM

Imagine this Tree scenario: <Homepage> <HeaderSection> <Navbar> <ShoppingCartComponent> </Navbar> </HeaderSection> <MainContent> <ShoppingCartComponent> &l ...

"document.createElement encounters an issue when used for creating a new window

I am currently working with two different HTML files: FirstWindow and SecondWindow. The FirstWindow is linked to FirstWindowJS.js, while the SecondWindow is linked to SecondWindowJS.js. The issue arises when I try to open SecondWindow.html using FirstWind ...

Alter the hues of the triangles on a threeJS plane

Is there a way to create a multicolor plane by changing the colors of the triangles within a mesh? Can the colors of triangles be adjusted in a PlaneGeometry object? ...

What steps should I take to resolve the issue of "Uncaught Error: [News] is not a <Route> component. All components within <Routes> should be either a <Route> or <React.Fragment>"?

I'm having trouble with version 6 of react-router-dom while trying to create a news app. Can anyone help me with fixing it? When I use the following code, I encounter this error: Uncaught Error: [News] is not a component. All component children of ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller public function show($id) { $structural = DB::table('attendance')->where('payroll_daily_id',$id) ->where('assignment','STRUCTURAL') -&g ...

Guide on changing the CSS of MUI parent components to set the display of buttons to 'block' in React

I'm facing a challenge with my modal design for mobile view. I need the buttons to display in a stacked format, one above the other, taking up the full width of the modal. I've been exploring ways to override the existing CSS within the component ...