Skip to content
Advertisement

Inner function does not return changes to variable assigned in outer function

I am attempting to modify the masterCounter variable within the timeKeyAdditionCheck function. Within the timeKeyAdditionCheck function, I successfully assign a value to masterCounter, but this change is not reflected within the scope of getEventsWithTime. When timeKeyAdditionCheck is complete, the value of masterCounter returns to null.

What changes do I need to make with timeKeyAdditionCheck function?

JavaScript
JavaScript

Advertisement

Answer

The reason I wasn’t getting the expected output for masterCounter was because, in the timeKeyAdditionCheckfunction, I thought I was making a copy of the object in the masterCounter array, but I actually created a reference instead. Here is the moment in my code when I unintentionally created a reference instead of a copy:

JavaScript

When I thought I was adding a unique object to the array, I was instead adding the reference to that same object at the end of the array.

I fixed it using the following code:

JavaScript

I used Object.assign() to create a copy of the last object in the array instead of creating another reference.

Advertisement