TIL Pure and Impure Functions
POSTED ON:
TAGS: functional-programming javascript clean-code
You might know that I am a proponent of Functional Programming, and I think Object Oriented Programming is overkill for most things in web development.
A important piece of Functional Programming is creating Pure Functions.
Easy Example #
// Pure Function
function addElements(valueOne, valueTwo) {
return valueOne + valueTwo;
}
// Impure function
function addElementsMaybe(valueOne, valueTwo) {
const random = Math.random() * 10;
return valueOne + valueTwo + random;
}
The side effect of addElementsMaybe()
is that you are never confident at what result you are getting back.
The benefit of Functional Programming is that you are able to 100% accurately predict what result you get.
But this example is lame.
How many people use Math.random()?
NOTE: I think people get confused by Pure functions in that they must write EVERYTHING to be Pure.
No no no no no. You will always have impure function in your code.
The idea is to make it as pure as you can to improve readablity.
Better Examples #
These are all Impure functions
// Impure function - API Calls
function getWebsiteData() {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
return myJson;
}
// Impure function - third-party APIs
function consoleLogThis(data) {
// console is from somewhere else!
console.log(data)
}
// Impure function - External dependency
var globalVal = 1;
function addWithGlobalVal(val1, val2){
// pure functions are self-contained. No globals!
return val1 + val2 + globalVal;
}
// Impure Function - Dom Manipulation
// Pure functions are supposed to return things.
// This changes things.
function addToList(string) {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
ul.appendChild(li);
}
Related TILs
Tagged: functional-programming