Skip to content

Instantly share code, notes, and snippets.

@zenius
Created May 3, 2019 12:37
Show Gist options
  • Save zenius/8e8151eb06851553161dc1e4f4abb0c2 to your computer and use it in GitHub Desktop.
Save zenius/8e8151eb06851553161dc1e4f4abb0c2 to your computer and use it in GitHub Desktop.
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