Pure functions are functions that have two characteristics:
- They do not produce side effects
- They will return the same output given a specific input
No side effects
When a function changes the external state, it is said to produce side effects. Pure functions should not produce side effects.
Returning the same output given a specific input
When you pass a set of input values into a pure function, it should always return the same output value. This is easier to explain with an example.
Let’s say you have a function called sum that sums two numbers together.
function sum(n1, n2) { return n1 + n2}If you pass 3 and 5 into sum, you will get 8. It doesn’t matter how many times you run sum(3, 5). You will always get 8. The output remains unchanged given the same input.
sum(3, 5) // 8sum(3, 5) // 8sum(3, 5) // 8sum(3, 5) // 8An impure function’s value can change given the same input. Let’s say for example you have the following function that uses Math.random.
function random() { return Math.random()}Math.random is a built-in JavaScript method that gives you a random value between 0 to 1. It changes each time you run it.
random() // 0.4656random() // 0.0037random() // 0.4346random() // 0.4989No external variables
Pure functions cannot depend on variables in the external state. This is because the output value will be different if the external state changes.
let num = 5function addValue(valueToAdd) { return num + valueToAdd}
addValue(10) // 15num = 100addValue(10) // 110Semi-pure functions
You can still write functions that relies on external variables if you know they won’t change.
const num = 5function addValue(valueToAdd) { return num + valueToAdd}
addValue(10) // 15addValue(30) // 35addValue(10) // 15Practice this with discretion.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson