Js to perform

  1. Lexical analysis stage: including analysis parameter, analysis variable declaration, analysis function declaration three parts. Through lexical analysis we write JS code into code that can be executed.
  2. Execution phase

Variable ascension

  • Only the declaration is promoted, initialization is not promoted
  • The declaration is promoted to the top of the current scope

🌰 1:

console.log(num)
var num
num = 6
Copy the code

After precompilation

var num
console.log(num) // undefined
num = 6
Copy the code

🌰 2:

num = 6
console.log(num)
var num
Copy the code

After precompilation

var num
num = 6
console.log(num) / / 6
Copy the code

🌰 3:

function bar() {
    if(! foo) {var foo = 5
    }
    console.log(foo) / / 5
}
bar()
Copy the code

After precompilation

function bar() {
    var foo // The declaration in the if statement is promoted
    if(! foo) { foo =5
    }
    console.log(foo)
}
bar()
Copy the code

Function increase

  • Function declarations and initializations are promoted
  • Function expressions are not promoted

🌰 1: Function declarations can be promoted

console.log(square(5)) / / 25
function square(n) {
    return n * n
}
Copy the code

After precompilation

function square(n) {
    return n * n
}
console.log(square(5))
Copy the code

🌰 2: Function expressions cannot be promoted

console.log(square) // undefined
console.log(square(5)) // square is not a function
var square = function(n) {
    return n * n
}
Copy the code

After precompilation

var square
console.log(square)
console.log(square(5))
square = function() {
    return n * n
}
Copy the code

🌰 3:

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

After precompilation:

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

The function is promoted before the variable is promoted

🌰 1:

console.log(foo) // The function is printed

function foo() {
    console.log('foo')}var foo = 1
Copy the code

🌰 2:

var foo = 'hello' // hello; (function(foo) {
    console.log(foo)
    var foo = foo || 'world'
    console.log(foo) //hello
})(foo)
console.log(foo) // hello
Copy the code

After precompilation

var foo = 'hello'; (function(foo) {
    var foo
    foo = 'hello' // Pass the value of the parameter foo
    console.log(foo) // hello
    foo = foo || 'world' // Foo has a value of hello, so it is not assigned to world
    console.log(foo) // hello
})(foo)
console.log(foo) Var foo = 'hello' var foo = 'hello'
Copy the code