vaibhav.yadav
Mon Sep 30 2024
Avoid Mutating Objects Loaded from JSON Files
Today I learned that even if data is loaded from a static JSON file - once it's parsed and stored as a JavaScript object in memory, it behaves like any other object—meaning it's mutable by reference.
This means that modifying a property of an object loaded from a JSON file will mutate the original object in memory, affecting all references to that object across the app.
To avoid accidental mutations, it's best to create a copy of the object (using methods like { ...obj }
for shallow copies) before modifying it. This ensures that the original data remains unchanged and helps prevent unexpected side effects throughout the codebase.
Example of creating a copy to avoid mutation:
const content = { ...emails['Signup success'] };
This protects the original emails
object from being modified, keeping the rest of the app safe from unintended changes.
It's a small but important detail when dealing with mutable JavaScript objects loaded from static sources!
#passByReference #js #json #objects