The Perils of Non-Local Mutation

One of the most important things to understand about JavaScript is how to deal with the mutable nature of objects. Unlike primitives (strings, numbers, booleans, etc.) objects are subject to modification.

Why does solarSystem think that both Earth and Mars are inhabited? Because simulateMarsSettlement directly modified it. Imagine how difficult it would be to debug if there were dozens of functions depending on the solarSystem object which suddenly changed.

We could code defensively by freezingsolarSystem so that it can't be modified. But this would only solve part of our problem. The underlying issue is that the functions are modifying an object which doesn't "belong" to them.

In general it is better to avoid modifying objects which are passed in as function arguments, because you may not know what else is depending on them. If you need a modified version of argument, then creating a copy is probably your best solution.