Advantages of global variables: You can reduce the number of variables and reduce the time consumption due to the data transfer of actual parameters and formal parameters.
Disadvantages of global variables: (1) Global variables are stored in the static storage area, the program starts to run the memory allocated for it, the program ends releasing the memory. Compared with the dynamic allocation and dynamic release of local variables, the lifetime is relatively long, so too many global variables will occupy more memory units. (2) The global variable destroys the encapsulation performance of the function. function like a black box, usually through the function parameters and return values for input and output, the function of the internal implementation is relatively independent. However, if a global variable is used in a function, the statement in the function body can be accessed by bypassing the function parameter and the return value, which destroys the function's independence and causes the function to rely on the global variable. At the same time, the portability of the function is reduced. (3) Global variables make the code readability of the function less readable. Because multiple functions may use global variables, the values of global variables may change at any time when the function is executed, which is detrimental to the troubleshooting and debugging of the program. Therefore, if it is not a last resort, it is best not to use global variables.
JS Global Variables pros and cons