Side Effect in JavaScript – Explained with Examples
A side effect occurs in a program whenever you use an external code in your function—which, as a result, impacts the function’s ability to perform its task.
Side Effect Example 1: How to Add an Old Value to a New One
let oldDigit = 5;
function addNumber(newValue) { return (oldDigit += newValue);}
In the snippet above, oldDigit
’s usage within the function gives addNumber()
the following side effects:
First side effect: Dependency on oldDigit
The fact that addNumber()
depends on oldDigit
to successfully perform its duties means that addNumber()
will return an error whenever oldDigit
is not available (or undefined
).
Second side effect: Modifies an external code
As addNumber()
is programmed to mutate oldDigit
’s state, it implies that addNumber()
has a side effect of manipulating some external code.
Third: Becomes a non-deterministic function
Using external code in addNumber()
makes it a non-deterministic function—as you can never determine its output by solely reading it.
In other words, to be sure of addNumber()
’s return value, you must consider other external factors—such as the current state of oldDigit
.
Therefore, addNumber()
is not independent—it always has strings attached.
Side Effect Example 2: How to Print Text to Your Console
function printName() { console.log("My name is Oluwatobi Sofela.");}
In the snippet above, console.log()
’s usage within printName()
makes the function have side effects.
How Does console.log
Cause a Function to Have Side Effects?
A console.log()
causes a function to have side effects because it affects the state of an external code—that is, the console
object’s state.
In other words, console.log()
instructs the computer to alters the console
object’s state.
As such, when you use it within a function, it causes that function to:
- Be dependent on the
console
object to perform its job effectively. - Modify the state of an external code (that is, the
console
object’s state). - Become non-deterministic—as you must now consider the
console
’s state to be sure of the function’s output.