Copying JavaScript Objects and Immutability

My Problem

I was seeing data “magically” changing on its own. It happened when I first swapped to JavaScript from Java and this is a topic I always seem to have to address to new developers.

Understanding the Problem

Well, basically in JavaScript primitives like Strings and Numbers are pass by value where as Objects are by reference. If you don’t copy objects properly you’ll change things unintentionally.

My Answer

If you need to copy an object use Object.assign(). Yes, the empty object in the first parameter is important. This will keep your objects immutable so they are not susceptible to surprise changes.