liveBook · Manning

Side effect

As explained in Grokking Simplicity

An observable interaction with state or the external environment that occurs in addition to producing a computation's return value.

A side effect is anything a function does besides returning a value. Sending an email, reading a file, modifying global state, making a web request, or blinking a light all count. These interactions are often the reason software exists, so functional programming does not eliminate them; it makes them easier to use and control. section 1.1 section 1.3 section 1.4

Use this distinction to reason about a function:

  • The explicit inputs are its arguments, and the explicit output is its return value. section 4.7
  • Information entering or leaving through any other channel is implicit and becomes a side effect. section 4.7
  • Side effects happen whenever the function is called, which can cause unintended behavior when only the return value is wanted. section 1.1
  • Replacing implicit inputs with arguments and implicit outputs with return values turns an action into a calculation. section 4.7

State changes alongside a return value

In add_to_total(amount), the amount is an explicit input and the returned total is an explicit output. Reading and modifying the global total, plus logging the old total, are additional interactions: side effects. section 4.7

var total = 0;
     

function add_to_total(amount) { #1
    console.log("Old total: " + total); #2 
    total += amount; #3
    return total; #4
 }

Inspect the function listing to separate its argument and return value from global-state access and console output. section 4.7

How Grokking Simplicity covers it

How deep it goes
Defines side effects, catalogs examples, and explains implicit inputs and outputs before stopping short of detailed control techniques.
Examples
Uses emails, files, lights, web requests, brakes, global state, console logging, and an accumulating total.
What you can do after
Apply explicit arguments and return values to identify or replace implicit inputs and outputs.
How it connects
Connects side effects with pure functions, impure functions, actions, calculations, and explicit inputs and outputs.

Also explained in

Compare how 24 books explain side effect →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.