What are Pure Functions in Javascript?
Published: 2023-09-04 19:04:15


## What are Pure Functions in Javascript?

### Write cleaner and programmer-friendly code with javascript pure functions

![Pure Functions](https://cdn-images-1.medium.com/max/2000/1*pOZrC3wm5QPugbmtZfUOpA.png)

As a developer, you need to write code that is cleaner and readable. Functional programming is a paradigm that will help you achieve this status. Pure functions are the atomic building blocks in functional programming. They are worshipped for their simplicity and testability. But what does “pure function” mean?

According to [JS guru — Eric Elliot](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0);
>  ***Functional programming **(often abbreviated FP) is the process of building software by composing **pure functions**, avoiding **shared state, ****mutable data, **and **side effects**. Functional programming is **declarative **rather than **imperative**, and the application state flows through pure functions. Contrast with object-oriented programming, where application state is usually shared and collocated with methods in objects.*

To understand pure functions in javascript, we will have a closer look at functions.

## What is a function?

A function is a process that takes an input also known as an argument, does some processing, and produces an output value. A function may serve the following purposes:

· **Mapping:** The output values are produced based on the input values. A function **maps** input values to output values.

· **Procedures:** A function can be called to perform a sequence of steps. The sequence is referred to as a procedure, and programming in this manner is referred to as **procedural programming**.

· **Input/Output(I/O):** Some functions provide communications with other parts of the system such as the screen, storage, system logs, or network.

For a procedure to qualify as a function, the mapping should take place.

### Define a function

There are a couple of ways to define a function in javascript:

A **function declaration **defines a named function. To create a function declaration you use the function keyword followed by the name of the function. When you are using function declarations, the function definition is *hoisted.* This allows the function to be used before it’s defined.
>  **Hoisting** is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before the code is executed. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

    function myName(parameters){
      statements
    }

A **function expression** defines an anonymous or named function. Anonymous functions are functions with no names. Function expressions are not hoisted, and therefore cannot be used before they are defined. In the example below, we are setting the anonymous function object equal to the variable “*myName*”.

    let myName = function(parameters){
      statements
    }

An **arrow function expression** is a shorter syntax for writing function expressions. Arrow functions do not create their own value.

    let name = (parameters) => {
      statements
    }

### Invoking a function

A function is executed when the function is called. This process is known as invocation. You can invoke a function by referencing the function name, followed by an open and closed parenthesis: (). Let’s explore an example.

In case you are using *Google Chrome*, open up your developer console so you can code along with these examples:

    [WINDOWS]: Ctrl + Shift + J
    [MAC]: Cmd + Opt + J

First, we will define a function named “*firstName*”. This function will take one parameter, “*name*”. When we execute the function it will log the name back to the console:

    function firstName(name){
      console.log(name);
    }

To invoke our function, we call it, while passing in the singular parameter. Here I am calling this function with the name *Bob*:

    firstName('Bob');
    // Bob

If the function has no parameters, you can invoke it with an empty set of parenthesis:

    function lastName(){
      console.log('Jackson');
    }

    lastName();
    // Jackson

## What is a Pure Function?

A pure function is a function that given the same input, will always return the same output, and produces no side effects. Its output or return value must depend on the input (arguments) and pure functions must return a value.

    function impure(argument) {
      finalScore = 100
      return argument * finalScore
    }

The above function is not pure because it modified a state **finalScore** outside its scope.

    function impure(argument) {
      let score = finalScore * argument
    }

The above function also isn’t pure because it didn’t return a value though it didn’t modify any external state.

    function impure(arguments) {
      return finalScore * 30
    }

The above function is impure, though it didn’t affect any external state, its output return finalScore * 30 isn’t dependent on the input **argument**. Not only must a pure function return a value but it must depend on the input.

    function pure(argument) {
      return argument * 35
    }

Here is a pure function. It didn’t cause any side effects, didn’t change an external state and it returns an output based on the input.

## Why you should use Pure Functions?

The major benefit of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments. They also make maintaining and refactoring code much easier. You can change a pure function without the need to worry about unintended side effects messing up the entire application. When used correctly the use of pure functions produces better quality code. It’s a cleaner way of working with lots of benefits.

## Conclusion

We have gone through the fundamentals of pure functions, how you can write them and utilize their power. With the power of pure functions, you will be able to write code that is cleaner, readable, and performant.

Thank you for reading & happy coding!