I have a function that returns an object with one of the properties being the value of a date object passed into it as a parameter (argument).
When this function is being called from within a loop, varying the date parameter sent into it and all of the returned objects are being added into an array - I noticed that all of the objects in the array ends up with the same value for the date object - which is the final value of the date from within the loop.
To demonstrate, I have a function (theFunction) that returns the string representation as well as the date parameter itself as two properties on the returned object.
This function is being called from another function (theLoop) that calls theFunction with different date values from within a loop and storing the results of the function calls into an array.
var theFunction = function (inputDate) {
/* The string representation and the date itself as properties on the returned object */
return {
string: inputDate.toLocaleString(),
original: inputDate
};
};
var theLoop = function (startDate) {
// declare an array for the output
var dates = [];
for (var minute = 0; minute < 1440; minute = minute + 30) {
var newHour = minute % 60,
newMinute = minute - newHour * 60;
// loop and increment the time by a half-hour starting from midnight until minutes < 1440
startDate.setHours(newHour, newMinute);
// record the output from theFunction into the array
dates.push(theFunction(startDate));
}
// return the array
return dates;
};
// get the array
var datesArray = theLoop(new Date());
// console.log the array
console.log(datesArray);
See this fiddle to run the above code.
Question 1: Why does the object returned from within the function named theFunction hold a reference to the date variable that is being incremented within the loop in theLoop?
Question 2: How can theFunction be changed so that it returns a copy of the date passed in to it?