TIL Not mutating in pure functions
POSTED ON:
TAGS: fp
It's nice to review the basics. This is about Functional Programming.
Functional Programming relies on pure functions.
That means:
-
same inputs return same outputs
-
No Side-Effects:
A few examples.
- Mutating input
- console.log
- HTTP calls (AJAX/fetch)
- Changing the filesystem (fs)
- Querying the DOM
Mutating inputs CAN cause side effects.
// This will change the <object> DIRECTLY.
const impureFunction = (key, value, object) => {
object[key] = value;
};
const person1 = {
name: 'Impure Rocky'
};
// notice that the original person1 was modified! CRAP!
const person1Modified = impureFunction('danceMoves', 'sweet' , person1);
console.log('person1', person1); // { "name": "Impure Rocky", "danceMoves": "sweet" }
console.log('person1Modified', person1Modified); // undefined
Rule of thumb: Always clone/copy the object. For Pure functions, never mutate it directly.
// This copies the object! So now you can do anything
const pureFunction = (key, value, object) => ({ ...object, [key]: value });
const person2 = {
name: 'Pure Rocky'
};
// notice that person2 was left alone, and person2Modified has the new data!
const person2Modified = pureFunction('danceMoves', 'sweet' , person2);
console.log('person2', person2); //{ "name": "Pure Rocky" }
console.log('person2Modified', person2Modified); //{ "name": "Pure Rocky", "danceMoves": "sweet" }
Also reminder that this example was a shallow clone.
via
https://medium.com/free-code-camp/what-is-a-pure-function-in-javascript-acb887375dfe
Related TILs
Tagged: fp