• There are only two types of scope in JS, global scope and function scope. Before ES6, JS had no block-level scope.
  • JavaScript code is executed in two phases. The first stage registers all variable and function declarations in the current lexical environment, which is simply parse. once parsed. the second stage of JavaScript execution begins!
  • There are two ways to create functions in JS: function declarations and function literals. Function promotion exists only in function declarations.
  • JavaScript only promotes declarations, not initialization. If you use a variable first and then declare and initialize it, the value of the variable will be undefined.
  1. All declarations are promoted to the top of the scope.
  2. The same variable is declared only once; others are ignored.
  3. Function declarations take precedence over variable declarations, and the function declaration is promoted along with the part of the function definition.

Examples of variable promotion:

num = 6; \var num = 7; \varnum; \console.log(num); // No error, output 7, also proves that variables are declared only once, others are ignored.
Copy the code

Examples of function promotion:

catName("Chloe");// Even before the declaration, the call can still be executed without error

function catName(name) {\
    console.log("My cat's name"+ name); The \}Copy the code

Example of a function being promoted higher than a variable when the function name is the same as the variable name:

func(); / / 1
var func;
function func() {
  console.log(1);
}
func = function() {
  console.log(2);
}
Copy the code

It prints 1, it doesn’t print 2. Both function and variable declarations are promoted, but it is important to note that functions are promoted before variables. var func; Although it precedes function func(), it is a repetitive declaration and is ignored because function declarations are promoted to precede normal variables.

Equivalent to this:

function func() {
  console.log(1);
}
func(); / / 1
func = function() {
  console.log(2);
}
Copy the code

Keep these three points in mind:

  1. Only the declaration itself is promoted, not the assignment operation.
  2. Variables are promoted to the top of their function, not the top of the entire program.
  3. Function declarations are promoted, but function expressions are not.