Created
May 3, 2019 12:37
-
-
Save zenius/8e8151eb06851553161dc1e4f4abb0c2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A function must pass two tests to be considered “pure”. | |
1. Same inputs always return same outputs | |
const add = (x, y) => x + y; | |
add(2, 4); // 6 | |
2. No side-effects | |
A few examples of side-effects are: | |
1. Mutating your input | |
2. console.log | |
3. HTTP calls (like AJAX/fetch) | |
4. Changing the filesystem | |
5. Querying the DOM | |
// code with side effects | |
const impureAssoc = (key, value, object) => { | |
object[key] = value; | |
}; | |
const person = { name: 'Bobo' }; | |
const result = impureAssoc('shoeSize', 400, person); | |
console.log(person); // { name: 'Bobo', shoeSize: 400 } | |
// code with no side side effects | |
const pureAssoc = (key, value, object) => ({ | |
...object, | |
[key]: value | |
}); | |
const person = { name: 'Bobo' }; | |
const result = impureAssoc('shoeSize', 400, person); | |
console.log(person); // { name: 'Bobo', shoeSize: 400 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment