DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on

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
Enter fullscreen mode Exit fullscreen mode
// Impure function.
let a = 4;
const multiplyNumbers = (b) => a *= b;

multiplyNumbers(3);
console.log(a); // first time: 12
> 12
multiplyNumbers(3);
console.log(a); // second time: 36
> 36

// Mutates external variable so it isn't pure.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode
// pure version of above.
addNumberarr = (arr, num) => {
return [...arr, num];
};
const testArr = [1,2,3];
addNumberarr(testArr, 4);
> [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

JS Built-in Pure functions:

arr.reduce()
arr.map()
arr.filter()
arr.concat()
arr.slice()
arr.each()
arr.every()
... - spread syntax 
Enter fullscreen mode Exit fullscreen mode

JS Built-in Impure functions:

arr.splice()
arr.push()
arr.sort()
Math.random()
Enter fullscreen mode Exit fullscreen mode

Thanks,

Follow: https://twitter.com/urstrulyvishwak

Top comments (0)