Skip to content
Related Articles

Related Articles

Improve Article
Pure Functions in JavaScript
  • Last Updated : 03 Feb, 2021

Pure Function is a function (a block of code ) that always returns the same result if the same arguments are passed. It does not depend on any state, or data change during a program’s execution rather it only depends on its input arguments.

Also a pure function does not produce any observable side effects such as network requests or data mutation etc.

Let’s see the below JavaScript Function:

function calculateGST( productPrice ) {
    return productPrice * 0.05;

The above function will always return the same result, if we pass the same productPrice. In other words, it’s output doesn’t get effected by any other values / state changes. So we can call “calculateGST” function as a Pure function.

Now, let’s see one more function below:

var tax = 20;
function calculateGST( productPrice ) {
    return productPrice * (tax / 100) + productPrice;

Pause a second and can you guess whether the above function is Pure or not ?

Yaayyy! You are right! It is not a pure function as the output is dependent on an external variable “tax”. So if tax value is updated somehow, then we will get a different output though we pass the same productPrice as a parameter to the function.

But here we need to make an important note:

Note: If a pure function calls a pure function, this isn’t a side effect and the calling function is still considered as pure. (Example: using Math.max() inside a function)

Below are the some side effects (but not limited to) which a function should not produce in order to be considered as a pure function –

  • Making a HTTP request
  • Mutating data
  • Printing to a screen or console
  • DOM Query/Manipulation
  • Math.random()
  • Getting the current time
My Personal Notes arrow_drop_up
Recommended Articles
Page :