Scope represents both a code area and a running environment

In JS, there are two scopes:

  • Global scope

Code written directly in a script

Variables declared in the global scope are promoted to the top of the script block and become properties of the global object.

  • Function scope

Code in a function

Variables declared in a function scope are promoted to the top of the function and do not become properties of the global object.

Therefore, the variables declared in the function do not cause pollution of the global object

Try to encapsulate functions in functions

However, when a function becomes an expression, it neither promotes nor pollutes the global object.

One way to turn a function into a function expression is to enclose the function in parentheses.

This way, however, the function cannot be called by name.

If a function expression is written and then called immediately, the function is called immediate executionIIFE(Imdiately Invoked Function Expression

Because in most cases, the function name of a function expression is meaningless, you can omit the function name.

A function without a name is called an anonymous function

Variables available in scope

Global scope can only use variables (including functions) declared in the global scope

A function scope can use not only variables declared in its own scope (including functions), but also variables of the external environment (including functions)

Sometimes, a function is more complex, in the process of writing, may need some other functions to assist it to complete some functions, and these functions will only be used by the function, not used elsewhere, you can declare these functions inside the function.

Function internally declared variables and external conflicts, use internal.