Pure and impure functions are concepts in functional programming that describe the behavior and characteristics of functions based on their interactions with external state and data.
Pure Functions:
- Deterministic: Given the same inputs, pure functions always produce the same output, regardless of any external factors. This property makes them predictable and reliable.
- No Side Effects: Pure functions do not modify the state of external variables, objects, or resources, nor do they perform any observable actions outside their scope, such as logging to the console or modifying files.
- Referential Transparency: Pure functions can be replaced with their return values without affecting the correctness of the program. This property facilitates reasoning about and optimizing code.
- Idempotent: Calling a pure function multiple times with the same inputs does not change the state of the program or produce different results.
Example of a Pure Function:
function add(a, b) {
return a + b;
}
This add function takes two arguments and returns their sum. It produces the same result for the same inputs every time it’s called, and it doesn’t modify any external state.
Impure Functions:
- Side Effects: Impure functions can modify external state or perform actions that have observable effects beyond returning a value. These side effects may include modifying variables, objects, or resources outside the function’s scope.
- Non-Deterministic: Impure functions may produce different results for the same inputs depending on external factors such as the state of the program, the environment, or the passage of time.
- Dependencies on External State: Impure functions may rely on or interact with external variables, objects, or resources, making their behavior unpredictable and harder to reason about.
- Not Referentially Transparent: Impure functions cannot be replaced with their return values without potentially altering the behavior of the program or causing unintended side effects.
Example of an Impure Function:
let sum = 0;
function addToSum(value) {
sum += value;
return sum;
}
This addToSum
function modifies the external variable sum
every time it’s called, causing side effects. Additionally, its return value depends on the current state of sum
, making it non-deterministic.
5 Functions Pure And Impure
To get a better understands of pure and impure functions within javacsript eco system, well look at the following javscript methods that are parts of javascript language and wrap our heads around why method is pure and why it’s impure.
Impure Functions
- Date.now(): Returns the current timestamp. Its return value depends on the current time, which can change between invocations.
- Math.random(): Generates a random number. Its return value is unpredictable and can vary between invocations.
- console.log(): Outputs data to the console. It has side effects and doesn’t return a value, making it impure.
- fetch(): Performs an asynchronous HTTP request. Its behavior depends on external factors such as network latency and server response time.
- fs.writeFile(): Writes data to a file on the filesystem. Its behavior depends on the state of the filesystem and can vary between invocations.
Pure Functions
- Math.max(): Returns the largest of zero or more numbers. Given the same input, it always returns the same output, without causing side effects.
- Array.map(): Creates a new array by applying a function to each element of an existing array. It doesn’t modify the original array and always returns a new array based on the input.
- String.toLowerCase(): Returns a new string with all alphabetic characters converted to lowercase. It doesn’t modify the original string and produces the same output for the same input.
- parseInt(): Parses a string argument and returns an integer. It always produces the same result for the same input string and doesn’t have side effects.
- Object.assign(): Copies the values of all enumerable own properties from one or more source objects to a target object. It creates a new object without modifying the source objects and returns the target object.
Lior Amsalem embarked on his software engineering journey in the early 2000s, Diving into Pascal with a keen interest in creating, developing, and working on new technologies. Transitioning from his early teenage years as a freelancer, Lior dedicated countless hours to expanding his knowledge within the software engineering domain. He immersed himself in learning new development languages and technologies such as JavaScript, React, backend, frontend, devops, nextjs, nodejs, mongodb, mysql and all together end to end development, while also gaining insights into business development and idea implementation.
Through his blog, Lior aims to share his interests and entrepreneurial journey, driven by a desire for independence and freedom from traditional 9-5 work constraints.
Leave a Reply