/ / Side Effect: Explained with 2 Helpful Examples

Side Effect: Explained with 2 Helpful Examples

Side effect depicted with code ovum

A 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.

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 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 as 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 alter the console object’s state.

As such, when you use it within a function, it causes that function to:

  1. Be dependent on the console object to perform its job effectively.
  2. Modify the state of an external code (that is, the console object’s state).
  3. Become non-deterministic, as you must now consider the console’s state to be sure of the function’s output.

All in all

Whenever you use an external code in your function, that code will cause side effects.

Credit

Get Helpful Resources in Your Inbox

A CodeSweetly Digest

Similar Posts