Skip to main content

Side effects

In short: A side effect is any action of a function that affects external state or depends on it, beyond the value it returns.


Detailed explanation

A side effect is any change outside the function itself: modifying global variables, printing to the console, making a server request, changing the DOM, working with files, and so on.

Functions with side effects are called impure, because they change the world outside themselves and make program behavior less predictable.


Examples of side effects

ExampleWhat it does
console.log('Hello')Changes the console (external environment)
alert('Hi!')Interacts with the user
document.body.style.color = 'red'Changes the DOM
fetch('/api')Makes an HTTP request
Math.random()Depends on external state (the random number generator)
Date.now()Depends on the current time
Modifying a global variableChanges program state outside the function

Example "with a side effect"

javascript
let count = 0; function increment() { count++; // modifies an outer variable }

Here the function does not just count, it also changes the state of the program.


Example "without side effects"

javascript
function add(a, b) { return a + b; }

This function works only with its own arguments and touches nothing around it.


Why this matters

Code without side effects:

  • is easier to test;
  • makes results easier to predict;
  • is safer for concurrent execution.

But! Some side effects are unavoidable - otherwise the program would not interact with the outside world (UI, server, file, etc.). The key is to isolate and control them.


SUMMARY

TraitSide effect
Changes external datayes
Depends on external stateyes
Returns different results for the same inputpossible
Exampleconsole.log, fetch, DOM operations
Without side effectsPure function

In one sentence:

A "side effect" is any external impact of a function (a change to or dependency on the environment), not directly related to the value it returns.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.