“This is the fifth day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.
Pure function is the basis of functional programming, before in the elegant coding article mentioned, write pure function, this article to briefly introduce the concept and difference of pure function and impure function.
Pure and impure functions
Pure functions:
When given the same input, pure functions always return consistent output, and never produce effects beyond the scope of the function, making them predictable. Pure functions are predictable no matter how many times they are executed.
- A predictable
- No side effects
The pure functions
Impure functions may not return consistent results when given the same input, and they may have effects beyond the scope of the function.
- unpredictable
- Have side effects
A predictable
Consider the following example:
const add = (a, b) => a + b;
console.log(add(2, 5));
Copy the code
For a=2 and b=3, the result of the function add is predicted to be 7, so the function above can be said to be pure.
Let’s look at the following code:
const add = (a, b) => a + b + parseInt(Math.random() * 10, 10);
console.log(add(2, 5));
Copy the code
Now this function is unpredictable because of the random number.
Side effects
Again, starting with the code, can you predict the output?
const globalVar = 1;
const add = (a, b) => a + b + globalVar;
console.log(add(2, 5));
Copy the code
So far, the result is a predictable 8, which seems right.
let globalVar = 1;
const add = (a, b) => a + b + globalVar;
globalVar = 0;
console.log(add(2, 5));
Copy the code
The output is 7, which seems predictable, but with globalVar, this is called a side effect.
Other side effects in front-end development:
- Dom manipulation: Dom manipulation exists in functions because Dom objects can be modified in many places.
const add = (a, b) => {
document.write("hello");
return a + b;
};
Copy the code
- External dependencies: Functions depend on script libraries outside the scope of the function.
let globalVar = 1;
const add = (a, b) => a + b + globalVar;
Copy the code
- consoleBecause:
console
External apis, not JavaScript methods.
const add = (a, b) => {
console.log(a + b);
};
Copy the code
fetch
,promise
, and any form of asynchronous function is impure because JavaScript is inherently synchronous.
Advantages of pure functions
Through the above introduction to the concept of pure and impure functions, now let’s see why we should write as many pure functions as possible:
- Easier to test, the results rely only on the input, when testing to ensure that the output is stable
- Easier to maintain and refactor, and you can write higher-quality code
- Easier to call without worrying about the side effects of the function, right
- The results can be cached because the same input always results in the same output