The side effects of functions can cause unnecessary troubles in program design, cause difficult-to-find errors to programs, and reduce program readability. Strictly functional languages require that functions have no side effects.
Several concepts related to Function side effects: Pure Function, Impure Function, and Referential Transparent.
Pure Function)
The input and output data streams are all Explicit. Explicit means that functions exchange data with the outside world only through one channel-parameters and returned values. All input information accepted by the function from outside the function is passed to the function through parameters. All information output from the function to the external function is passed to the external function through the return value.
Impure Function)
In contrast. Implicit (Implicit) means that functions exchange data with the outside world through channels other than parameters and return values. For example, reading/modifying global variables is called implicit data exchange with the outside world.
Referential Transparent)
Reference the concept of transparency is related to the side effects of the function and is affected by it. If two identical expressions in the program can replace each other anywhere in the program without affecting the action of the program, then the program has reference transparency. Its advantage is that it is easier to understand and not so obscure than non-reference transparent language semantics. Pure Functional Languages have no variables, so they all have reference transparency.
The following example illustrates the combination of reference transparency and function side effects.
Copy codeThe Code is as follows: result1 = (fun (a) + B)/(fun (a)-c );
Temp = fun ();
Result2 = (temp + B)/(temp-c );
If the function has no side effects, result1 and result2 are equivalent. However, if fun has side effects, such as adding B or c to 1, result1 and result2 are not equal. Therefore, the side effects violate the transparency of reference.
Functions are introduced in JavaScript. But obviously, functions in JS can access and modify global variables (or variables defined outside the function), as follows:Copy codeCode: var a = 5;
Function fun (){
A = 10;
}
Fun (); // a is changed to 10
To ensure that functions have no side effects in Javascript, you can only rely on the habits of programmers, that is
1. Function entry uses parameter operations without modifying it
2. The function does not modify variables outside the function, such as global variables.
3. The calculation result is returned to the external (exit) through the function)