Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What is a side effect?

Oluwatobi Sofela

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.

Example 1: Add an old value to a new one

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:

First: Dependency on oldDigit

The fact that addNumber() depends on oldDigit to successfully perform its duties means that whenever oldDigit is not availableor undefined, addNumber() will return a faulty result.

Second: Modifies an external code

As addNumber() is programmed to mutate oldDigit’s state, it implies that addNumber() has a side effect where it manipulates the external code.

Third: Becomes a non-deterministic function

The use of an external code in addNumber() makes it a non-deterministic functionyou 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.

Example 2: Print text onto 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 codethe 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.



View all Courses

Keep Exploring