Notes

Side effects and Pure functions in JS functions

Edit on GitHub

JavaScript
2 minutes

Side effects

Side effects, is when a function is effecting things outside of itself. When any of the inputs or any of the outputs are indirect.

  • Indirect input, i.e. was not part of the parameters
  • Indirect output i.e. was not returned from the function

A function without any side effects can not access anything from outside itself and it can not assign to anything from outside of itself. In functional programming, you don’t want any side effects.

 1function shippingRate() {
 2  rate = ((size + 1) * weight) + speed
 3}
 4
 5var rate
 6var size = 12
 7var weight = 4
 8var speed = 5
 9shippingRate()
10rate // 57
11
12size = 8
13speed = 6
14shippingRate()
15rate // 42

Notice how in the above example, the shippingRate() had no parameteres passed in (i.e. no direct input), and the function didn’t return anything, i.e. no direct output. Yet it still changed the value of the rate variable. The following example is the fixed, functional way of writing that function

1function shippingRate(size, weight, speed) { // parameters = direct input
2  return ((size + 1) * weight) + speed // return = direct output
3}
4
5shippingRate(12, 4, 5) // 57
6shippingRate(8, 4, 6) // 42

Some examples of side effects are:

  • Accessing and changing variables outside the function call
  • I/O (console, files, etc.)
  • Network Calls
  • Manipulating the DOM
  • Timestamps
  • Generating random numbers
  • Any function that’s blocking the execution of another function

Some side effects are impossible to avoid. The goal is to minimize side effects. And make them obvious when we must have them.

Pure functions

A function with its inputs direct, its outputs direct and without any side effects is a pure function.

1// pure
2function addTwo(x,y) { // direct input
3  return X + y // direct output
4}
5
6//impure
7function addAnother(x,y) {
8  return addTwo(x,y) + z // where'd that z come from?
9}

However, if you are accessing constant values that will not be reassigned inside your function, than that’d also be functional programming (according to Kyle Simpson). The fact that it is a constant should be obvious to the reader of your code.

 1const z = 1
 2
 3// pure
 4function addTwo(x,y) { // direct input
 5  return X + y // direct output
 6}
 7
 8//impure
 9function addAnother(x,y) {
10  return addTwo(x,y) + z // z is a constant value in the function's scope
11}
12
13addAnother(20,21) // 42