What is pure function ? Pure function in JavaScript

Pure functions are the atomic building blocks in functional programming. They are adored for their simplicity and testability. A pure function is a deterministic function. This means when a same input is passed every time, the function will return same output.

Pure Function checklist:

  1. Same inputs always return same outputs
  2. No side-effects.

Same input and same output:

whenever you pass same input any time then you will get same result every time.

Example:

let sum = (x, y) => x + y;
add(4, 2); // 6
add(4, 2); // 6
add(4, 2); // 6

As you can see above we are passing same input every time we are getting same result.

let x = 2
let sum = (y) => x += y;
add(4); // 6
add(4); // 10
add(4); // 14

In above code we can see even we are passing same input but not getting same output. So this is not a pure function.

No side-effect:

A few examples of side-effects are

  1. Mutating your input
  2. console.log
  3. HTTP calls (AJAX/fetch)
  4. Changing the filesystem (fs)
  5. Querying the DOM

Basically any work a function performs that isn’t related to calculating the final output. Unrelated task of function may cause side effect.

const impureAssoc = (key, value, object) => {
  object[key] = value;
};

const person = {
  name: 'Bobo'
};
const result = impureAssoc('shoeSize', 400, person);
console.log({
  person,
  result
});

In above function you can see that it is modifying the input parameter directly which is not good as pure function. We can modified it to make it pure function like this.

const pureAssoc = (key, value, object) => ({
  ...object,
  [key]: value
});

const person = {
  name: 'Bobo'
};
const result = pureAssoc('shoeSize', 400, person);
console.log({
  person,
  result
});

above function is almost pure function but above function may act as impure function when we will pass nested object. In that case we need to use deepcopy of object.

What is pure function ?

1. A function’s pure if it’s free from side-effects and returns the same output, given the same input.
2. Side-effects include: mutating input, HTTP calls, writing to disk, printing to the screen.

How we can achieve pure function ?

1. You can safely clonethen mutate, your input. Just leave the original one untouched.
2. Spread syntax ( syntax) is the easiest way to shallowly clone objects.
3. JSON.parse(JSON.stringify(object)) is the easiest way to deeply clone objects.

Source

Leave a Reply