Categories
JavaScript Answers

How to alter and assign JavaScript object properties without side effects?

Spread the love

Sometimes, we want to alter and assign JavaScript object properties without side effects.

In this article, we’ll look at how to alter and assign JavaScript object properties without side effects.

How to alter and assign JavaScript object properties without side effects?

To alter and assign JavaScript object properties without side effects, we should make a copy of the original object before assigning new properties to the copied object.

For instance, we write:

const a = {
  id: 0,
  value: 1
}
const b = {
  ...a,
  id: 1
}
console.log(a === b)
console.log(b)

to make a copy of a with the spread operator and then we the id property to 1.

We can see that the console log logs false so we know a and b aren’t referencing the same object.

And we see that b is {id: 1, value: 1}.

Conclusion

To alter and assign JavaScript object properties without side effects, we should make a copy of the original object before assigning new properties to the copied object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *