I suppose this might be a duplicate, but I have been unable to find an explanation yet.
Here is my sample code:
const makeCalendar = () => {
const calendar = {};
calendar.xmas = ['December', 25];
calendar.newYear = ['January', 1];
return (day) => calendar[day];
}
calendar = makeCalendar();
const xmasArray = calendar('xmas');
console.log(calendar('xmas')); // [ 'December', 25 ]
xmasArray[1]++;
console.log(calendar('xmas')); // [ 'December', 26 ]
Since elements of the xmasArray
are mutable, I can change the variables inside the scope of makeCalendar()
and so corrupt the closure it returns. The only way I found to tackle this issue is to return an anonymous array [...calendar[day]]
(instead of calendar[day]
), which then blocks the access inside makeCalendar()
.
My questions are: is it the right way to deal with this problem? Are there better ways? Probably I don't understand correctly what's going on...