Last active
April 11, 2022 15:35
-
-
Save renton4code/e391ba6effd248d17894fccad700317a to your computer and use it in GitHub Desktop.
Pure function vs impure function
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
const pureMultiplyItemsBy = (arrayOfNumbers, multiplier) => { | |
return arrayOfNumbers.map(_ => _ * multiplier); | |
} | |
const impureMultiplyItemsBy = (arrayOfNumbers, multiplier) => { | |
for (let i = 0; i < arrayOfNumbers.length; i++) { | |
arrayOfNumbers[i] *= multiplier; | |
} | |
return arrayOfNumbers; | |
} | |
let x = [1,2,3]; | |
pureMultiplyItemsBy(x, 2); | |
console.log(x); // [1,2,3] - no side effects | |
let y = [1,2,3]; | |
impureMultiplyItemsBy(y, 2); | |
console.log(y); // [2,4,6] - side effect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment