How to change a property on an object without mutating it with JavaScript?

Sometimes, we want to change a property on an object without mutating it with JavaScript.

In this article, we’ll look at how to change a property on an object without mutating it with JavaScript.

How to change a property on an object without mutating it with JavaScript?

To change a property on an object without mutating it with JavaScript, we can use the object spread operator.

For instance, we write:

const additions = {
  x: "Bye"
}
const a = {
  x: "Hi",
  y: "Test"
}
const b = {
  ...a,
  ...additions
}
console.log(b)

We create the b object by merging the entries of a with the entries of additions.

The entries that are merged in later overrides the ones that are merged in earlier if they have the same key.

So b.x is 'Bye'.

Therefore, b is {x: 'Bye', y: 'Test'}.

Conclusion

To change a property on an object without mutating it with JavaScript, we can use the object spread operator.