Pure & Impure Function

In this post we are going to know Pure & Impure Function.

Pure Function

In Functional JavaScript a Pure Function is a function that doesn’t depend on anything outside of it’s scope nor modify it and always returns the same output for the same input arguments.

Pure Functions are deterministic. They are predictable because they always produce the same output for the same input.

An example of a Pure Function can be,

function pureFunction(param) {
  return param * 2;
}

pureFunction(5)// 10

pureFunction(10)// 20

pureFunction(15)// 30

This is an example of a Pure Function. The pureFunction() expects a parameter(param), if the param is 5 then the result will be 10, for input 10 the output will be 20 & for input 15 the output will be 30. The function is predictable, always produce the same output for same input.

Impure Function

To understand the Impure Function we need to understand Side Effects.

Side Effects

Side Effects mean the change of a global state or interaction with outside element(database, web service). If you write a function that only does a console.log(), this is a side effect.

There are things that considered as side effects.

  • Changing global variables.
  • Calling a web service.
  • Updating the database.
  • Showing alert or console statement.
  • Updating the DOM.

If any of those happen in a function that will not considered as a pure function rather than it will considered as an impure function.

Here is an example of an impure function, updating a global state,

let name = "Mark"

function impureFunction() {
  name = "John"
  return name
}

console.log(impureFunction()) //"John"

The impureFunction() function mutates the name variable(global).

Example of an impure function that is interacting with a web service using axios.

function getUsers() {
  axios.get('https://jsonplaceholder.typicode.com/users')
    .then(res => console.log(res))
    .catch(err => console.log(err))
}

getUsers()

4 thoughts on “Pure & Impure Function

Leave a Reply

Your email address will not be published. Required fields are marked *