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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read