Going the straightforward JavaScript way
One of the biggest causes of side effects was the possibility of a function modifying its arguments or global objects. All non-primitive objects are passed as references, so if/when you modify them, the original objects will be changed. If we want to stop this (without just depending on the goodwill and clean coding of our developers), we may want to consider some straightforward JavaScript techniques to prohibit those side effects:
- Avoiding mutator functions that directly modify the object that they are applied to
- Using
const
declarations to prevent variables from being changed - Freezing objects so that they can’t be modified in any way
- Creating (changed) clones of objects to avoid modifying the original
- Using getters and setters to control what is changed and how
- Using a functional concept – lenses – to access and set attributes
Let’s take a look at each technique in more detail...