A simple intro to pure functions in JavaScript.

Photo by CHUTTERSNAP on Unsplash

A simple intro to pure functions in JavaScript.

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. - MDN

Pure functions are an integral aspect of functional programming. A pure function must suffice the following conditions -

  • It must be predictable.

  • It must not change any input value.

  • It should have only one unit of logic.

  • It must not have any side effects.

  • It must be testable.

Pure functions operate on IPO. Now you might be wondering, what is IPO?

  1. Input
  2. Processing
  3. Output

For example - Writing a raised to function in JS.

const num = 8;
function squared(number) {
  return Math.pow(number, 2)
}
const output = squared(num);
console.log({ num, output })
// { num: 8, output: 64 }

No matter how much the volume of usage, it will work as expected. Another example of a pure function can be the increment function used in counters.

const initialvalue = 0;
const increment = (number) => number + 1
const incrementedvalue = increment(initialvalue);
console.log({ initialvalue, incrementedvalue })
// { initialvalue: 0, incrementedvalue: 1 }

Pure functions abstract a specific logic out to increase code reusability. It also helps us to drive the DRY principle. If your function is dependent on any other variable other than the arguments passed to it, then it's not a pure function. A pure function has zero side effects.

What are the side effects of an impure function?

The side effects of an impure function include unexpected mutation of function arguments, DOM mutation, XHR/fetch call, etc. For example - The functional logic to add an element to an array.

// Impure function
const array = [1, 4, 16, 64];
function addtoarray(array, element) {
  array.push(element);
  return array;
}
const output = addtoarray(array, 2);
console.log({ array, output });
// { array: [ 1, 4, 16, 64, 2 ], output: [ 1, 4, 16, 64, 2 ] }

As you can see, the argument is mutated. Argument mutation must be avoided while writing pure functions.

// Pure function
const array = [1, 4, 16, 64];
function addtoarray(array, element) {
  return [...array, element];
}
const output = addtoarray(array, 2);
console.log({ array, output });
// { array: [ 1, 4, 16, 64 ], output: [ 1, 4, 16, 64, 2 ] }

As you can see, the argument is not affected function logic.

Quick summary

  • Pure functions are simple reusable functions.
  • Pure functions take at least one argument, process it, and give an output.
  • Pure functions have zero side effects.
  • Pure functions only have a unit logic.
  • Pure functions are highly testable.

    Focus only on your inputs and output while being a non-interventionist observer of external mess. - Pure Function