The deeper an identifier is located in JavaScript, the slower it is to read and write. Therefore, reading and writing local variables in a function is always the fastest, while reading and writing global variables is usually the slowest. A good rule of thumb is: if a cross-scope value is referenced more than once in a function, store it in a local variable.
For example:
This function references document three times, and document is a global object. The process of searching for this variable must traverse the entire scope chain until it is finally found in the global variable object. You can reduce the impact on performance by first storing a reference to a global variable in a local variable, and then using this local variable instead of the global variable.
For example: