Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 29, 2022 06:34 am GMT

javascript: Pure Function

Two Rules

  1. Given the same input, always return same output.
  2. 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,

Follow: https://twitter.com/urstrulyvishwak


Original Link: https://dev.to/urstrulyvishwak/javascript-pure-function-1gjf

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To