Tip 11: Create Objects Without Mutations Using Object.assign()
In this tip, you’ll learn how to update an object without mutations, using Object.assign().
Mutation problem in objects
In the previous tip, you took a quick look at objects and got rules for when they offer distinct advantages over other collections. Still, you need to be careful when using them because they can leave you open to the same problems with mutations and side effects that you saw in arrays. Casually adding and setting fields on objects can create unseen problems.
Consider a very common problem. You have an object with a number of key-values pairs. The problem is that the object is incomplete. This happens often when you have legacy data and there are new fields, or you are getting data from an external API and you need it to match your data model. Either way, the issue is the same: you want to fill in the remaining fields using a default object.
Updating data without mutation
How can you create a new object that preserves the original data while adding in the defaults? And, of course, you don’t want side effects or mutations.
Take a moment to write out the code. See what you come up with.
If you wrote the code out, it would probably look something like this:
Get hands-on with 1400+ tech skills courses.