Side effect occurs in a program whenever you use an external code in your function, which impacts the function’s ability to perform its task.
let oldDigit = 5;function addNumber(newValue) {return oldDigit += newValue;}// 5+5 = 10
In the snippet above, oldDigit
’s usage within the function makes addNumber()
have the following side effects:
The fact that addNumber()
depends on oldDigit
to successfully perform its duties means that whenever oldDigit
is addNumber()
will return a faulty result.
As addNumber()
is programmed to mutate oldDigit
’s addNumber()
has a side effect where it manipulates the external code.
The use of an external code in addNumber()
makes it a
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 as it always has strings attached.
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.
A console.log()
causes a function to have side effects because it affects console
object’s state
In other words, console.log()
instructs the computer to alter 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.