Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptPure Functions in JavaScript

Pure Functions in JavaScript

A 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:

Javascript




function calculateGST(productPrice) {
    return productPrice * 0.05;
}
console.log(calculateGST(15))


The above function will always return the same result if we pass the same product price. In other words, its output doesn’t get affected by any other values/state changes. So we can call the “calculate GST” function a Pure Function.

Output:

0.75

Now, let’s see one more function below:

Javascript




let tax = 20;
function calculateGST(productPrice) {
    return productPrice * (tax / 100) + productPrice;
}
console.log(calculateGST(15))


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

If you guessed that it isn’t, you are right! It is not a pure function as the output is dependent on an external variable “tax”. So if the tax value is updated somehow, then we will get a different output though we pass the same productPrice as a parameter to the function.

Output:

18

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 pure. (Example: using Math.max() inside a function)

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

  • Making an HTTP request
  • Mutating data
  • Printing to a screen or console
  • DOM Query/Manipulation
  • Math.random()
  • Getting the current time

RELATED ARTICLES

Most Popular

Recent Comments