Understanding the Difference between Pure and Impure Functions in JavaScript
Last Updated :
22 May, 2023
In this article, we will see the concepts of pure and impure functions in JavaScript, along with understanding their differences, & basic implementation for a better understanding of the concepts.
Pure Functions: This function always returns the same output as given the same input parameters. Pure functions only depend on their input parameters and don't affect the state of the application or other parts of the code.
The Side effect/leaking does happen when the function tries to utilize any external code inside the function, which in turn, impacts the ability of the function to perform that specific task for which the function is built.
Characteristics:
- Functions do not modify any state or have any side effects.
- Functions only depend on their input parameters.
- These are predictable and have a deterministic behavior and are easier to test, debug, and maintain.
Advantages:
- Pure functions are easier to test because they have predictable behavior and do not modify any state or have side effects.
- These can be composed together to create complex behaviors, and the composition is also pure.
- Pure functions are used to memoize performance improvements since the same input will always return the same output and is less likely to introduce bugs or unexpected behavior in the code.
Disadvantages:
- Pure functions can be more difficult to write when the problem requires state changes or side effects.
- They require additional overhead to pass all necessary data as input parameters.
Example 1: This example describes the Pure function, Here, geek() is a pure function as it always returns the same output given the same input parameter. It does not modify any state or leave effects on the code. When the function geek is called it passes the output through the inside function and returns the value.
JavaScript
function geek(value) {
return value+100;
}
console.log(geek(34));
console.log(geek(4));
console.log(geek(12));
For instance, geek(34) will return the output as 100+34 = 134. We can clearly see that It's doesn't modify the entire code.
Example 2: In this example, the capitalize() function takes a string as an input parameter and returns a new string with all characters in uppercase. Since it does not modify any state or have side effects, it is a pure function.
JavaScript
function capitalize(str) {
return str.toUpperCase();
}
console.log(capitalize('geeks')); // Output: GEEKS
console.log(capitalize('world')); // Output: WORLD
Impure Functions: Impure functions are functions that can modify the state of the application or have side effects. In other words, impure functions can have unpredictable behavior and do affect other parts of the application.
Characteristics:
- Functions can modify the state of the application or have side effects.
- Functions depend on other parts of the code.
- These are unpredictable and can have a non-deterministic behavior and are harder to test, and maintain.
Advantages:
- They can have side effects or modify the state of the application, which is necessary for many tasks such as I/O operations or DOM manipulation.
- Impure functions are easier to write and may require fewer input parameters.
- Functions are more flexible and adaptable to different use cases.
Disadvantages:
- Impure functions are more difficult to reason about and test because their behavior can be unpredictable and depend on other parts of the code.
- Functions can introduce bugs or unexpected behavior in the code.
- They can be more difficult to compose together to create complex behaviors.
Example 3: In this example, the incrementflag() is an impure function because it modifies the flag variable which is outside the scope. The first time incrementflag() called flag value increased to 1 and print it in the console. But when the second time called, the increment() function increased the previous value of flag and 1, and the updated value is 2. So this impure function increment modifies the flag along with the state.
JavaScript
let flag = 0;
function incrementflag() {
flag++;
}
incrementflag();
console.log(flag);
incrementflag();
console.log(flag);
Example 4: In this example, the getRandomNumber() function generates a random number between 0 and 9 each time it is called, which is a side effect. Therefore, it is an impure function. Also, note that the function can have different outputs even with the same input (none in this case).
JavaScript
function getRandomNumber() {
return Math.floor(Math.random() * 10);
}
console.log(getRandomNumber());
console.log(getRandomNumber());
Differences between Pure and Impure Functions:
Features | Pure Functions | Impure Functions |
---|
State Modification | Does not modify the state of the application | It can modify the state of the application |
Dependency | Only depends on its input parameters | It can be dependent on other parts of the code |
Testing | Easier to test | harder to test |
Maintenance | It is easier to maintain | It is harder to maintain |
In summary, pure functions have several advantages over impure functions such as being easier to test, debug, and maintain. Pure functions only depend on their input parameters and do not modify the state of the application or have side effects. Impure functions, on the other hand, can have unpredictable behavior and can modify the state of the application or have side effects.
Similar Reads
Difference between Methods and Functions in JavaScript
Grasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and funct
3 min read
Difference between First-Class and Higher-Order Functions in JavaScript
Understanding the difference between first-class and higher-order functions in JavaScript is important. These are big concepts in programming, especially in the kind of coding used for making websites. This article is all about explaining what they are, how they are used, and why they are so importa
3 min read
Difference Between Function Overloading and Function Overriding in JavaScript
Function overloading and function overriding are two important concepts in object-oriented programming (OOP). Function overloading allows the creation of multiple functions with the same name but different parameters. Function overriding allows the subclass or child class to provide the specific imp
3 min read
Difference between Anonymous and Named functions in JavaScript
In JavaScript or in any programming language per say, functions, loops, mathematical operators and variables are the most widely used tools. This article will tell you about the difference between anonymous functions and named functions. We will discuss all the required concepts in this article to k
4 min read
What is the difference between freeze and seal in JavaScript?
In JavaScript, Object.freeze makes an object immutable, preventing any changes to existing properties and values. Object.seal allows changes to existing properties but prevents adding or removing properties. Both methods enforce strict immutability, but freeze is stricter than seal. Table of Content
2 min read
What is the difference between unshift() and Push() method in JavaScript?
JavaScript Unshift() method is very much similar to the push() method but the difference is that the unshift() method adds the elements at the very beginning of the array whereas the push() method adds at the end of the array. Javascript Array unshift() method: The JavaScript Array unshift() Method
2 min read
Difference between forEach() and map() loop in JavaScript
The forEach() and map() methods in JavaScript are used to iterate over arrays, but they serve different purposes. forEach() executes a provided function once for each array element without returning a new array, while map() transforms elements and returns a new array.JavaScript forEach() JavaScript'
4 min read
Explain the difference between undefined and not defined in JavaScript
In JavaScript, they both are related to memory space and there is a very simple difference between them. If the variable name which is being accessed doesn't exist in memory space then it would be not defined, and if exists in memory space but hasn't been assigned any value till now, then it would b
3 min read
What is the difference between Map and WeakMap in JavaScript ?
In this article, we will talk about the difference between Map and WeakMap which are introduced by ES6. Javascript object supports only one key object. For supporting multiple key objects, Then Map comes on this path. Map: A Map is an unordered list of key-value pairs where the key and the value can
4 min read
What is the difference between find() and filter() methods in JavaScript ?
In this article, we will see the difference between the find() and filter() methods in javascript. JavaScript find() method: The find() method is used to find all the descendant elements of the selected element. It finds the element in the DOM tree by traversing through the root to the leaf. Syntax:
2 min read