StackOverflow question: Why does a JavaScript function that returns an object does it by reference (to its arguments)?
http://stackoverflow.com/questions/32857579/why-does-a-javascript-function-that-returns-an-object-does-it-by-reference-to-i
by Ori Drori
HTML
<pre id="output"></pre>
JavaScript
var theFunction = function (inputDate) {
/* The string representation and the date itself as properties on the returned object */
var inputDateClone = new Date(inputDate);
return {
string: inputDateClone.toLocaleString(),
original: inputDateClone
};
};
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);
// print the array
document.querySelector('#output').innerHTML = JSON.stringify(datesArray, null, 4);
// QUESTION: Why would the `original` values be all the same???