An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
September 29, 2022 06:34 am GMT
Original Link: https://dev.to/urstrulyvishwak/javascript-pure-function-1gjf
javascript: Pure Function
Two Rules
- Given the same input, always return same output.
- Produces no side effects
Use: Easy to refactor, makes code more flexible and adaptable.
Case 1
// Pure function.const multiplyNumbers = (x,y) => x * y;multiplyNumbers(2, 3);> 6
// Impure function.let a = 4;const multiplyNumbers = (b) => a *= b;multiplyNumbers(3);console.log(a); // first time: 12> 12multiplyNumbers(3);console.log(a); // second time: 36> 36// Mutates external variable so it isn't pure.
Case 2
// Impure function.addNumberarr = (arr, num) => {arr.push(num);};const testArr = [1,2,3];addNumberarr(testArr, 4);console.log(testArr);>[1, 2, 3, 4]// Mutates input array so it isn't pure.
// pure version of above.addNumberarr = (arr, num) => {return [...arr, num];};const testArr = [1,2,3];addNumberarr(testArr, 4);> [1, 2, 3, 4]
JS Built-in Pure functions:
arr.reduce()arr.map()arr.filter()arr.concat()arr.slice()arr.each()arr.every()... - spread syntax
JS Built-in Impure functions:
arr.splice()arr.push()arr.sort()Math.random()
Thanks,
Original Link: https://dev.to/urstrulyvishwak/javascript-pure-function-1gjf
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To