Detailed examples of variable and function promotion in JavaScript

Detailed examples of variable and function promotion in JavaScript

js execution

  • Lexical analysis phase: includes three parts: formal parameter analysis, variable declaration analysis, and function declaration analysis. Through lexical analysis, the js code we write is converted into executable code.
  • Execution Phase

Variable Hoisting

  • Only declarations are hoisted, initializations are not hoisted
  • Declarations are hoisted to the top of the current scope.

🌰 1:

console.log(num)
var num
num = 6

After precompilation

var num
console.log(num) // undefined
num = 6

🌰 2:

num = 6
console.log(num)
var num

After precompilation

var num
num = 6
console.log(num) // 6

🌰 3:

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

After precompilation

function bar() {
    var foo // declaration hoisted inside if statement if (!foo) {
        foo = 5
    }
    console.log(foo)
}
bar()

Function promotion

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

🌰 1: Function declarations can be hoisted

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

After precompilation

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

🌰 2: Function expressions cannot be hoisted

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

After precompilation

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

🌰 3:

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

After precompilation:

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

Function hoisting precedes variable hoisting

🌰 1:

console.log(foo) // will print out the function function foo() {
    console.log('foo')
}
var foo = 1

🌰 2:

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

After precompilation

var foo = 'hello'
;(function(foo) {
    var foo
    foo = 'hello' // The value of foo passed in as parameter console.log(foo) // hello
    foo = foo || 'world' // foo has the value hello, so it is not assigned the value world
    console.log(foo) // hello
})(foo)
console.log(foo) // hello, prints var foo = 'hello' in the global scope

The order of JS variable promotion and function promotion

Recently, I encountered a question in a written test that examined the order of variable hoisting and function hoisting. Before, I only knew that variables defined by var would be hoisted and function declarations would also be hoisted, but I did not study their order and detailed process in depth. After consulting the information and verifying it myself, I came to my own understanding of their order. Without further ado, let's get straight to the point.

First of all, I would like to give my conclusion: function promotion has a higher priority than variable promotion, and will not be overwritten by a variable with the same name when it is declared, but will be overwritten after the variable with the same name is assigned a value.

You can see the following code:

     console.log(a) // Æ’ a(){} Before assigning a value to variable a, function a will be printed.
     var a=1;
     function a(){}
     console.log(a) // 1 After variable a is assigned, the value printed will be the value of variable a

First, both variable and function declarations are hoisted, but the function hoisting priority is higher than the variable. After both are hoisted, the variable is only defined without assignment, so the output is function a. The detailed process is as follows:

     function a(){} // Function declaration promotion a->fa (){}
     var a; // Variable promotion console.log(a) // At this time, variable a is just declared without assignment, so it will not overwrite function a --> Output function afa (){}
     a=1; //Variable assignment console.log(a) // At this time, variable a is assigned --> Output the value of variable a 1

Summary: Since both function declarations and variables are hoisted, if a function has the same name as a variable, then the function will be printed before the variable is assigned a value, and the value of the variable will be printed after the variable is assigned a value.

Now let's look at another piece of code:

     a(); // 2
     var a = function(){ // Treat it as a function assigned to variable a
        console.log(1)
     }
     a(); // 1
     function a(){
        console.log(2)
     }
     a(); // 1

In fact, I just want to tell you that only function declarations will be hoisted, not function expressions. Therefore, the code after the function expression will output 1, because the variable a is assigned to overwrite the hoisted function a. The detailed process is as follows:

     function a(){ // Function promotion console.log(2)
     }
     var a; // variable promotion a(); // 2  
     a = function(){ // After the variable a is assigned, it will overwrite the function a above
         console.log(1)
     }
     a(); // 1
     a(); // 1

Let’s look at another piece of code:

     a();
     function a(){
         console.log(1)
     }
     function a(){
         console.log(2)
     }

What is printed is 2. The reason is simple: the one declared first will be overwritten by the one declared later.

Summarize

This is the end of this article about variable hoisting and function hoisting in JavaScript. For more relevant js variable hoisting and function hoisting content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Let’s learn about JavaScript variable scope
  • Detailed explanation of variable scope in JavaScript
  • Do you know variable declaration in JavaScript?
  • JavaScript Advanced Programming: Variables and Scope
  • How to turn local variables into global variables in JavaScript
  • JavaScript variables and transformation details

<<:  A brief understanding of MySQL SELECT execution order

>>:  Detailed explanation of the principle of Docker image layering

Recommend

Writing methods that should be prohibited in native JS

Table of contents Block-level functions Directly ...

Implementing a simple Christmas game with JavaScript

Table of contents Preface Achieve results Code CS...

Super detailed basic JavaScript syntax rules

Table of contents 01 JavaScript (abbreviated as: ...

Introduction to the use of MySQL performance stress benchmark tool sysbench

Table of contents 1. Introduction to sysbench #Pr...

MySQL paging analysis principle and efficiency improvement

MySQL paging analysis principle and efficiency im...

MySQL 8.0.13 installation and configuration method graphic tutorial

This article shares the installation and configur...

Introduction to RHCE bridging, password-free login and port number modification

Table of contents 1. Configure bridging and captu...

Learn SQL query execution order from scratch

The SQL query statement execution order is as fol...

Vue realizes cascading selection of provinces, cities and districts

Recently, I need to implement a cascading selecti...

Docker installation tutorial in Linux environment

1. Installation environment Docker supports the f...

Two methods to disable form controls in HTML: readonly and disabled

In the process of making web pages, we often use f...

JavaScript to show and hide the drop-down menu

This article shares the specific code for JavaScr...

Summary of common commands in Dockerfile

Syntax composition: 1 Annotation information 2 Co...

Methods and steps for deploying multiple war packages in Tomcat

1 Background JDK1.8-u181 and Tomcat8.5.53 were in...