0

Can this arrow function be written so that the firstOfMonth value is preserved?

const today = new Date();
const firstOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
console.log("First Day Of Month: " + firstOfMonth.getDay());
//"First Day Of Month: 3"

const firstSunday = fDate => new Date(fDate.setDate(fDate.getDate() - fDate.getDay()));
console.log("First Sunday: " + firstSunday(firstOfMonth));
//"First Sunday: Sun Apr 28 2019 00:00:00 GMT-0400 (Eastern Daylight Time)"

console.log("First Day Of Month: " + firstOfMonth.getDay());
//"First Day Of Month: 0"
rew
  • 375
  • 2
  • 13
  • Because you call `fDate.setDate` which mutates the Date object you've passed in. Which is the `firstOfMonth` object. – VLAZ May 12 '19 at 17:19
  • I get that, but doesn't fDate replace firstOfMonth in the Arrow function, ie: fDate becomes a working copy of the firstOfMonth object? – rew May 12 '19 at 17:50
  • [No](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language), [it doesn't](https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference). The *value* of an variable that holds an object is the *reference* to the object. So when you pass that variable in a function call, you get a copy of the *reference* in the function, thus you have direct control of the object. For primitives, you get a copy of the value, too, but the value *is* the primitive, hence why you can't "modify" say, a string variable outside the function. – VLAZ May 12 '19 at 18:09

0 Answers0