DEV Community

Amit Kumar Singh
Amit Kumar Singh

Posted on • Edited on

Pure and Impure Function in JavaScript: JS Quick Guide

So this article will be about what is functions in JavaScript and, most importantly, what is pure and impure function in JavaScript and how to differentiate between pure and impure functions.

Pure and Impure Function in JavaScript: JS Quick Guide

Table of Contents

  • What are functions
  • What are Pure Functions
  • What are Impure Functions
  • Conclusion

What are Functions in JavaScript
So before we know what are functions in JavaScript, we all know that JavaScript is a scripting language which means we can write our code line by line and save it as a script file name dot JS and JavaScript will execute that script file. Now the question is, why do we need a function?

So once the script file becomes very big, it becomes tough to identify and debug what a particular line of code is doing, and this is where JavaScript functions come into the picture; functions are the beauty of JavaScript. It helps to wrap a particular piece of script and helps to identify what a particular set of script is doing or what it is required to do.

Now let us understand functions with a few examples:

function sayHello() {
  console.log(‘Hello’);
}
sayHello(); // Hello
Enter fullscreen mode Exit fullscreen mode

In the above example, we have created a function named sayHello(), and once we execute this function, it will print hello in our console. So now, only by seeing the function we can know or identify what a particular set of function is doing.

Now let’s take another example to understand function more clearly,

function fullName(firstname, lastname) {
  console.log(`${firstname} ${lastname}`);
}
fullName(‘Amit’, ‘Singh’) // Amit Singh
Enter fullscreen mode Exit fullscreen mode

So in the above example, we have declared a function named fullName(), which takes two arguments: the first name and the last name, and prints the full name by taking the first name and the last name as arguments.

Now just by seeing the function code, we can identify what the particular set of function is doing or what it is required to do. It becomes very easy to debug a particular piece of code, which is why we use pure functions in javascript.

Now depending upon our need or requirement, we can create a set of functions in JavaScript to make our work easier and to debug a particular piece of code. For example, we can create a function to add a number, multiply a number, etc.

So as we have understood what functions are, will help us know better about pure and impure functions in JavaScript.

What is Pure function
So basically, pure functions are a type of function in JavaScript that is pure in nature. By this, I mean this function will always produce the same output for the same given input, and there will be no side effects. These pure functions are independent and do not depend on any external state or variables.

Now let us understand pure functions with few examples:

function fullName(firstname, lastname) {
  console.log(`${firstname} ${lastname}`);
}
fullName(‘Amit’, ‘Singh’) // Amit Singh
Enter fullscreen mode Exit fullscreen mode

We have taken the same example we discussed above; we have declared a function named fullName(), which takes a first name and last name as arguments and gives the output, which is the full name.

So we can see that the output was very predictable for this function, which is why we call this kind of function a pure function where the output of a particular function is predictable, only depends on the internal state, and does not have any side effect. Pure functions can be reused in our code wherever we require the same output; this makes the program very modular.

Here are the key characteristics of pure functions:

  • Deterministic: A pure function always returns the same result when given the same arguments. It does not depend on any hidden or mutable state.
  • No Side Effects: Pure functions do not modify variables outside their scope, mutate data structures, perform I/O operations, or have any other observable effect on the program’s state or the external world.
  • Referential Transparency: Pure functions can be replaced with their return value without changing the program’s behavior. For a given set of inputs, calling a pure function will always yield the same output, regardless of where or when it is called.

Now by the above example, we can see that pure function has several advantages.

  • Predictability: Since pure functions produce the same output for the same input, they are predictable and easier to reason about. You don’t need to worry about hidden state changes affecting their behavior.
  • Testability: Pure functions are easier to test because you can provide inputs and check the outputs without dealing with complex setup or dependencies.
  • Reusability: Pure functions can be reused in different parts of your codebase, promoting code modularity and reducing redundancy.
  • Parallelization: Pure functions can be safely executed in parallel since they do not rely on a shared mutable state. This property is beneficial for performance optimization.

What is Impure Function
So impure functions are functions that are impure in nature. I mean that given the same input, it will give different output. We can see that impure functions are the opposite of what we discussed above in pure functions.

So unlike pure functions, an impure function can depend on any external state and can also modify the external state, mutate data, perform input-output operation, or have other observable effects on the program state or the external state. Impure functions can be used in scenarios where we need to interact with external states. For example, let’s check if a particular user is authenticated, and based on that, we will do a certain set of actions.

isUserAuthenticated() is a function that returns true or false based on the user’s situation if the user is logged in or not.

function isUserLoggedIn() {
  const isAuthenticated = isUserAuthenticated() // return true or false;
  if(isAuthenticated) {
      console.log(`user is logged in`)
   } else {
      console.log(`user is not logged in`)
   }
 }
Enter fullscreen mode Exit fullscreen mode

Now in the above example, we see that we have a function named is isUserAuthenticated(), which returns true or false based on the user situation if the user is logged in or not, and then we have declared a function named isUserLoggedIn() which depends on the external state that is a function isUserAuthenticated() and check if a user is authenticated or not and based on the state it gives the output.

So now, by seeing the function isUserLoggedIn(), we cannot predict the output because the output is based on the external state. Whether the user is authenticated or not, it will give the output.

Let us understand this by a simple example:

let c = 2
function add(a,b) {
  console.log(a+b+c)
}
add(1,2);
Enter fullscreen mode Exit fullscreen mode

In the above example, we have declared a function named add(). It takes two arguments, a and b, and returns the sum of a + b + c; we can clearly see that function add() depends on the external state, i.e., variable c for the output, and the output will never be the same for the given input.

Now let us understand by another example:

function generateUserId(){
  console.log(Math.floor(Math.random()*10000));
}
Enter fullscreen mode Exit fullscreen mode

In the above example, we have created a function named generateUserId(), which basically generates a random user id using that external state; in this case, that is Math.random() functions. We can see that it becomes very difficult to predict the output of the generateUserId() function.

Here are some characteristics of impure functions:

  • Side Effects: Impure functions can have side effects, meaning they can modify variables outside their scope, mutate data structures, perform I/O operations (e.g., reading from or writing to a file or database), make network requests, update the user interface, or interact with the browser’s APIs.
  • Dependency on External State: Impure functions can rely on variables or data that are not passed as function parameters. They can access and modify external state, such as global variables or properties of objects outside their local scope.
  • Non-deterministic: Impure functions may produce different results for the same input because they can depend on external factors or changing state.

Conclusion
In this article, we have covered what is functional programming, what are functions in JavaScript, why do we use functions in JavaScript, what are pure and impure functions in JavaScript, and what the differences are between impure and pure functions. So we can conclude that every function has its importance, whether pure or impure, depending on the situation or requirement. We can use pure or impure functions to make our code clean and can be easy to debug.

👋🏻 👋🏻 Hey if you are here, please connect with me
Instagram / Twitter / LinkedIn

Top comments (0)