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
| Example | What 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 variable | Changes program state outside the function |
Example "with a side effect"
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"
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
| Trait | Side effect |
|---|---|
| Changes external data | yes |
| Depends on external state | yes |
| Returns different results for the same input | possible |
| Example | console.log, fetch, DOM operations |
| Without side effects | Pure 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 readyA concise answer to help you respond confidently on this topic during an interview.