05 Pure functions
Lesson goal Learn to tell pure functions from impure ones and to rewrite impure ones so that they return a new value instead of mutating outside data.
Pure functions are extremely important. A pure function is not necessarily idempotent, though: x => x + 1 is pure, but applying it to its own result gives a new value. If you need side effects, group them into separate functions and keep them apart from pure functions. Every program, especially on the web, needs side effects (mutating the DOM tree, requests to the server (fetch), reading from a file (readFile), and so on).
// An IMpure function
// ===============================
let user = { name: 'John', age: 25 }
const changeAge = () => user.age = 30
// we mutate an outer variable and create side effects
// the program will behave unpredictably, since several functions
// may work with this variable, and a bug will be harder to track down
changeAge()
console.log(user) // { name: 'John', age: 30 }
// ===============================// Code like this is acceptable if we create independent modules with their own closure
// ===============================
// useChangeUser :: Object -> Object
const useChangeUser = (user) => {
let userBase = structuredClone(user) // be sure to clone
const changeAge = (newAge) => userBase.age = newAge
// to work with the data from outside
return {
userBase,
changeAge
}
}
// But even in this case it is better to do this
// useImmutableUser :: Object -> Object
const useImmutableUser = (user) => {
let userBase = structuredClone(user) // be sure to clone
const changeAge = (newAge) => userBase = ({
...userBase, // or structuredClone(userBase) or JSON.parse(JSON.stringify(userBase))
age: newAge
})
// to work with the data from outside
// getUser always returns the current object: changeAge replaces it with a new one
return {
getUser: () => userBase,
changeAge
}
}
const john = useImmutableUser({ name: 'John', age: 25 })
const before = john.getUser()
john.changeAge(30)
console.log(john.getUser()) // { name: 'John', age: 30 } the change is visible from outside
console.log(before) // { name: 'John', age: 25 } the previous object has not changed
// ===============================// Now let's fix the example above
// ===============================
let user = { name: 'John', age: 25 }
// A pure function
// changeAge :: (Number, Object) -> Object
const changeAge = (newAge, user) => ({
...user,
age: newAge
})
// let's improve it
// in case we need deep cloning and currying
// changeAgeCurried :: Number -> Object -> Object
const changeAgeCurried = (newAge) => (user) => ({
...structuredClone(user), // or JSON.parse(JSON.stringify(user))
age: newAge
})
// let's check everything here
const changedUser = changeAgeCurried (30) (user)
console.log(user) // { name: 'John', age: 25 } kept its original state
console.log(changedUser) // { name: 'John', age: 30 } we got a new user without side effects
// ===============================Key points
- A pure function is not necessarily idempotent: x => x + 1 is pure, but applying it to its own result gives a new value.
- Every program, especially on the web, needs side effects: mutating the DOM, requests to the server, reading from a file. Group them into separate functions and keep them apart from pure functions.
- A function that mutates an outer variable creates side effects: several functions may work with that variable, and a bug will be harder to track down.
- A pure function does not change the object passed to it but returns a new one: with spread, or with structuredClone if deep cloning is needed.
- Even in a module with its own closure, it is better to replace the state with a new object than to mutate it.
Exercises
Exercise 1
The addTagImpure function changes the post passed to it. Write a pure addTag: it returns a new post with the tag added and leaves the original alone. Keep in mind that tags is a nested array: if you copy only the object itself, the array stays shared.
Starter code
// addTagImpure :: (String, Object) -> Object
// IMpure: it changes the post passed to it
const addTagImpure = (tag, post) => {
post.tags.push(tag)
return post
}
// addTag :: (String, Object) -> Object
// your code
const post = { title: 'FP', tags: ['js'] }
const taggedPost = addTag('fp', post)
console.log(post.tags) // the original post has not changed
console.log(taggedPost.tags)Expected output
[ "js" ] [ "js", "fp" ]
Show solution
// addTagImpure :: (String, Object) -> Object
// IMpure: it changes the post passed to it
const addTagImpure = (tag, post) => {
post.tags.push(tag)
return post
}
// addTag :: (String, Object) -> Object
// Pure: a new object and a new tags array, the original post is not changed
const addTag = (tag, post) => ({
...post,
tags: [...post.tags, tag],
})
const post = { title: 'FP', tags: ['js'] }
const taggedPost = addTag('fp', post)
console.log(post.tags) // the original post has not changed
console.log(taggedPost.tags)Exercise 2
The result of finalPriceImpure depends on the outer variable discount: with the same argument, the function returns a different price once discount has changed. Write a pure finalPrice that receives the discount percentage as an argument. Run the code and compare the lines before and after discount changes.
Starter code
let discount = 10
// finalPriceImpure :: Number -> Number
// IMpure: the result depends on the outer variable discount
const finalPriceImpure = (price) => price - price * discount / 100
// finalPrice :: (Number, Number) -> Number
// your code
console.log(`impure: ${finalPriceImpure(200)}, pure: ${finalPrice(10, 200)}`)
discount = 50 // someone changed the outer variable
console.log(`impure: ${finalPriceImpure(200)}, pure: ${finalPrice(10, 200)}`)Expected output
impure: 180, pure: 180 impure: 100, pure: 180
Show solution
let discount = 10
// finalPriceImpure :: Number -> Number
// IMpure: the result depends on the outer variable discount
const finalPriceImpure = (price) => price - price * discount / 100
// finalPrice :: (Number, Number) -> Number
// Pure: everything the result depends on comes in as arguments
const finalPrice = (percent, price) => price - price * percent / 100
console.log(`impure: ${finalPriceImpure(200)}, pure: ${finalPrice(10, 200)}`)
discount = 50 // someone changed the outer variable
console.log(`impure: ${finalPriceImpure(200)}, pure: ${finalPrice(10, 200)}`)Playground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.