02 Pure Functions in Javascript
Tags: javascript, functional, react, webdev
Published: 2024-05-15 05:30:05

---
title: 02 Pure Functions in Javascript
published: true
description: what are pure functions.
tags: #javascript #functional #react #webdev
cover_image: https://i.imgur.com/OOtbTwc.png
# Use a ratio of 100:42 for best results.
# published_at: 2024-04-24 05:41 +0000
---

### What is Function

A function is the process which takes some input called arguments and produce some output called return values.
Function may serve different purposes like Procedures and I/O.

#### Procedures
A function may be called to perform a sequence of steps, the sequence is known as procedures, A function should return something, by default a function return undefined, So Programming in this style called Procedural Programming.
For example:
```javascript
function multiplyNumbers(x=1, y=1) {
  const value = x * y;
  console.log(value)
}
```
The above code is an example of Procedure the reason behind this is that it returned nothing from function body.

#### I/O

some functions exist to communicate with other parts of system such as screen, storage etc.

```javascript
function alertUser(){
  alert("Welcome to the world of Functions")
}
```


### What are Pure functions

> A Pure function is a function that always gives the same output for the same input and doesn't do something extra.

Pure function is all about mappings, for each input there exist an output.
For example `slice` and `splice` they both are array methods but serves different purposes.
**Slice** is pure because it returns the same output every time if same input is passed.

```javascript
const vowels = ['a', 'e', 'i', 'o', 'u'];

vowels.slice(0, 3) // ['a', 'e', 'i']
vowels.slice(0, 3) // ['a', 'e', 'i']
vowels.slice(0, 3) // ['a', 'e', 'i']
```

**Splice** method will changes the contents of an array by removing or replacing the existing elements in the array.

```javascript
vowels.splice(0, 3) // ['a', 'e', 'i']
vowels.splice(0, 3) // ['o', 'u']
vowels.splice(0, 3) // []
```
In functional Programming we dont use methods like `splice` which mutates the data.

let's see another example to understand it better.
```javascript
let minAgeForVote = 18;

const canVote = voterAge => voterAge >= minAgeForVote
```
the above code snippet is impure because `minAgeForVote` is mutable variable i.e.  `minAgeForVote` can be modified later in the program which may provide unwanted result. 
To fix this we can do something like this

```javascript
function canVote(voterAge) {
  const minAgeForVote = 18;
  return voterAge >= minAgeForVote;
}
```

### what are the Side Effects

> A side effect is a change of system state or observable interaction with the outside world that occurs during the calculation of a result.
>
> <cite>Brian Lonsdorf [1]</cite>
[1]: https://mostly-adequate.gitbook.io/mostly-adequate-guide/ch03#side-effects-may-include

Side effects are list are so long but majorly are 
1. Writing on Screen
2. Querying a DOM
3. Writing in console
4. Making an Http Request
5. Mutations.

### Application of Functional Purity

**1. Testable:-** Pure functions are very easy to test, because we do not need to mock anything, we just give input and expect the output for the same.

**2. Parallel Code:-** Pure functions are completely independent of outside state. Their independent nature makes them great candidate for Parallel processing across many CPU's.

**3. Referential Transparency:-** You can replace a function call with its result without changing the behaviour of your program. So if a function consistently return the same output for the same input and doesnt cause any side effect in your code called `Referential Transparent`.
  ```javascript
    function add(x, y) {
      return x + y;
    }

    const result1 = add(3, 5);
    const result2 = add(3, 5);

    console.log(result1); //  8
    console.log(result2); //  8
  ```
In this example, the `add function` is `referentially transparent` because it doesn't have any side effects. It always returns the same output `(x + y)` for the same inputs `(x and y)`, making it safe to replace function calls with their return values without affecting the program's behavior.

`Pure functions` are predictable, easy to test, and enable better code maintainability and reasoning. They promote `immutability` and functional programming principles by avoiding changes to global state and ensuring that function calls are deterministic and independent of external factors.

Happy Learning!!