Created
December 22, 2019 12:14
-
-
Save bhaveshdaswani93/829c318736b30c0b324b56c7e991c951 to your computer and use it in GitHub Desktop.
Pure function that does not generate side effect
This file contains 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
// In this example i want to clear out the difference between function with side effect and a function without side effect | |
let arr = [1,2,3]; | |
function removeLastItem(input) { | |
input.pop(); | |
} | |
removeLastItem(arr); | |
console.log(arr); // output [1,2] (this function changes the orignal variable from [1,2,3] -> [1,2]) | |
// above execution has side effect as it mutate arr which belong to the outside world. | |
function immutablyRemoveLastItem(input) { | |
const newArray = [].concat(input); // concat method copies the value to new variable. | |
return newArray.pop(); | |
} | |
let newArr = [1,2,3]; | |
console.log(immutablyRemoveLastItem(newArr)); // output [1,2] | |
console.log(newArr); // output [1,2,3] -> the above function does not have side effect as it not modify the orignal input instead it copies | |
// and alter the copied array. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment