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
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
22 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...