Understanding Pure and Impure Functions in Javascript
Published: 2023-07-09 09:51:47

---
title: Understanding Pure and Impure Functions in Javascript
published: true
date: 2022-06-25 20:02:47 UTC
tags: 
canonical_url: 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pv5huhevwswolats0m7r.png
---

# Introduction

Before my migration into ReactJs, I never knew about functions being pure or impure. I only understand functions as a set of statements that performs a task or calculates a value.

But after my migration to react, I learnt so much about javascript and functions and I'll be sharing my knowledge on javascript functions in today's article.

# What are functions in javascript?

From the definition of [W3schools](https://www.w3schools.com/js/js_functions.asp)

A JavaScript function is a block of code designed to perform a particular task. JavaScript function is executed when "something" invokes it (calls it).

# Pure functions

A _pure function_ is a function that returns a value that's computed based on its arguments. Pure function takes in at least one argument and always returns a value or another function. They do not cause **side effects** , **set global variables** , or change anything about **application state**. They treat their arguments as immutable data.

In order to understand pure function, let's first take a look at an impure function:

```typescript
const frederick = {
   name: "frederick douglass",
   canRead: false,
   canWrite: false
  }

Function selfEducate(){
  frederick.canRead = true;
  frederick.canWrite = true;
  return frederick 
 }

selfEducate()
console.log(frederick)

// { name: "frederick douglass", canRead: true, canWrite: true}
```

The selfEducate function is not a pure function. It does not take any arguments, it does not return a value or a function, it also changes a variable outside it's scope _frederick_. Once the selfEducate function is invoked, something about the _"world"_ has changed. It causes `side effect`.

Another example of an impure function is:

```typescript
const frederick = {
   name: "frederick douglass",
   canRead: false,
   canWrite: false
  }

const selfEducate = person => {
  person.canRead = true;
  person.canWrite = true;
  return person
 }

console.log(selfEducate(frederick))
console.log(frederick)

// { name: "frederick douglass", canRead: true, canWrite: true}
// { name: "frederick douglass", canRead: true, canWrite: true}
```

### Pure functions are testable

Pure functions are naturally _testable_. They do not change anything about their environment or _"world"_, and therefore do not require a complicated test setup or teardown. Everything a pure function needs, it accesses via arguments. When testing a pure function, you control the arguments, and thus you can estimate the outcome. The second **selfEducate** function above is also impure. It causes **side effects**. Invoking the function mutates the objects that are sent to it. If we could treat the arguments sent to the function as immutable data, then we would have a pure function.

> Let's have this function take an argument:

```typescript
const frederick = {
   name: "frederick douglass",
   canRead: false,
   canWrite: false
  }

const selfEducate = person => ({
  ...person,
  canRead: true,
  canWrite: true 
})

console.log(selfEducate(frederick))
console.log(frederick)

// { name: "frederick douglass", canRead: true, canWrite: true}
// { name: "frederick douglass", canRead: false, canWrite: false}
```

Finally, this version of selfEducate is a pure function. It computes a value based on the argument that was sent to it: the **person**. It returns a ne person object without mutating the argument sent to it and therefore has no side effects.

> Now let's examine an impure function that mutates the **DOM**

```javascript
  function Header(text){
  let h1 = document.createElement("h1");
  h1.innerText = text;
  document.body.appendChild(h1);
}

Header("Header() caused side effects");
```

The Header function creates a heading-one element with specific text and adds it to the DOM. This function is impure. It does not return a function or a value, and it causes side effects: a changed DOM.

In React, the UI is expressed with pure function. In the following sample below, Header is a pure function that can be used to create h1 elements just like the previous example. However, this function on it's own does not cause side effects because it does not mutate the DOM. This function will create an h1 element, and its up to some other part of the application to use that element to change the DOM:

```javascript
  const Header = props => <h1>{props.title}</h1>;
```

Pure functions are another core concepts of functional programming. They will make your life much easier because they will not affect your application's state.When writing functions, try to follow these three rules:

1. The function should take in at least one argument.
2. Te function should return a value or another function.
3. The function should not change or mutate any of it's arguments.

# Data Transformation

How does anything change in an application if the data is immutable?. Functional programming is all about transforming data from one form to another. We'll produce transformed copies using functions. These functions make our code less imperative and thus reduce complexity.

You don not need a special frameork to understand how to produce one dataset that is based upon another. Javascript already has the necessary tools for the task built into the language. They are two core functions you must master in order to be proficient with functional javascript: Array.map and Array.reduce. For the sack of simplicity, i'll be talking about those two function in another episodes of my blog.

# Conclusion

That wil be all for thi section. if you find thi article helpful, then click on the follow button to get more updates and helpful resources on _javascript_, _Reactjs_ and _Nextjs_. You can also follow me on twitter [@o\_sunday15](https://twitter.com/O_sunday15) to get useful resources and tech trends.