# Pure vs Impure Functions

## Visual Overview

Functional Programming utilizes functions to create programs and focuses on separating pure functions from impure functions.

## General Overview

### Properties

Pure functions have 3 properties, but the third (marked with `*`) is expanded to show its full weight:

PurePure ExampleImpureImpure Example
Given an input, will it always return some output?Always
(Total Functions)
`n + m`Sometimes
(Partial Functions)
`4 / 0 == undefined`
Given the same input, will it always return the same output?Always
(Deterministic Functions)
`1 + 1` always equals `2`Sometimes
(Non-Deterministic Functions)
`random.nextInt()`
*Does it interact with the real world?NeverSometimes`file.getText()`
*Does it access or modify program stateNever`newList = oldList.removeElemAt(0)`
Original list is copied but never modified
Sometimes`x++`
variable `x` is incremented by one.
*Does it throw exceptions?NeverSometimes`function (e) { throw Exception("error") }`

In many OO languages, pure and impure code are mixed everywhere, making it hard to understand what a function does without examining its body. In FP languages, pure and impure code are separated cleanly, making it easier to understand what the code does without looking at its implementation.

Programs written in an FP language usually have just one entry point via the `main` function. `Main` is an impure function that calls pure code.

Sometimes, FP programmers will still write impure code, but they will restrict the impure code to a small local scope to prevent any of its impurity from leaking. For example, sorting an array's contents by reusing the original array rather than copying its contents into a new array. Again, impure code is not being completely thrown out; rather, it is being clearly distinguished from pure code, so that one can understand the code faster and more easily.