Let’s do one more: variable promotion and scope

var a = 10;
(function () {
    console.log(a) // output: undefined
    a = 5
    console.log(window.a) // Output: 10
    var a = 20;
    console.log(a); // Output: 20}) ()// If executed in a browser, node displays an error window is not defined
Copy the code

A simpler analysis

  1. In the immediate function, var a = 20; The local variable a is promoted to the top of the body of the immediately executed function due to js’s variable declaration promotion mechanism. Since such promotion does not include assignment, the first print statement will print undefined, and the last print statement will print 20.

  2. A = 5 due to variable declaration promotion; This statement is executed when the local variable a has already been declared, so the effect is to assign a value to the local variable A, while window.a is still the original 10.

Is equivalent to:

var a = 10;
(function () {
    var a; // In the function scope, the variable is promoted to this point
    console.log(a) 
    a = 5
    console.log(window.a) // here window.a is in global scope
    a = 20;
    console.log(a); }) ()Copy the code

Advanced analysis

  1. Function scopes have access to global scopes
var a = 123;
(function(){
  console.log(a) / / 123
  a = 456} ());console.log(a) / / 456
Copy the code

Step analysis:

var a = undefined;
a = 123;
(function(){
  console.log(a) // the function scope looks for variable A
  console.log(window.a) // If the variable is not found, it will be searched up until it is found. If it is not found, it will be declared undefined
  window.a = 456 // The window variable 'a' will be modified because the window variable 'a' is found} ());console.log(a) / / 456
Copy the code

Implicit declarations are actually involved here, so I’ll explain them below

  1. The global scope cannot access variables in the local scope
(function(){
  var a = 456} ());console.log(a) // Error: a is not defined
Copy the code

The window is already in the global scope, so the variable a is not defined

  1. When the local scope is implicitly declared, the variable is declared in the global scope by default
(function(){
  a = 456} ());console.log(a) / / 456
Copy the code

See also and thanks

  • Wood and poplar front end advanced
  • Variable scope, closure