Pure Function JavaScript

Pure Function JavaScript

·

3 min read

Functions

People think that computer science is the art of geniuses but the actual reality is the opposite, just many people doing things that build on each other, like a wall of mini stones. Donald Knuth

Functions are the bread and butter of JavaScript programming. The concept of warping a piece of code in a block has many values. In JavaScript, functions are first-class citizens. First-class citizens mean that functions can do everything that others can.

  • Functions can be assigned to a variable

  • Functions can be passed as an argument

  • Functions can be returned from a function

A program is a collection of blocks of code that are called functions. Functions in programming are the same as function in Math let's take an example In Math we write functions like this f(x)=x+2 This simply means that a function takes x as an input and return x+2. Let's now create a program of the above function.

function addTwo(x){
return x+2
}

The addTwo is the programming implementation of f(x)=x+2 in this function. The addTwo function is a Pure function

Pure Function

For a function to be pure it has to meet the following two conditions,

  • *** Given the same input the same output should be returned. ***

  • No side effects.

Let's now try to defend our statement about the addTwo function being pure. we will have to check if the addTwo function meets the above-mentioned conditions if it does then we will be successful in defending our statement.

*** Given the same input the same output should be returned *** let's pass 2 as an input.

console.log(addTwo(2))
 It will return 4

Now it doesn't matter how many times we pass the value of 2 the function addTwo will always return 4. So it is clear that our addTwo function satisfies the first condition of the Pure function.

Let's now try to verify the second condition.

*** No Side Effects ** what is a side effect? When a function modifies or relies on anything outside of its parameters then the function has side effects.

The above function of ours is not using anything outside of its parameter which means that it satisfies the second condition of pure function.

It is concluded that our *** addTwo function is a pure function***

A principle of identifying a pure function.

Why you should use pure functions?

  • Easy to refactor and move around.

  • Independent of the outside world.

  • Simplest reusable block of code.

  • Immune to bugs outside of its scope.

  • Makes programs more adaptable to future changes

Conclusion

A computer program is a collection of small blocks of code that are called functions. A pure function is a function that when given the same input will return the same output and a pure function doesn't have side effects. Pure functions are independent of outside and can easily be refactored.