Home Web Front-end JS Tutorial Detailed explanation of Hoisting in JavaScript

Detailed explanation of Hoisting in JavaScript

Aug 20, 2017 am 10:10 AM
javascript js

Function declarations and variable declarations are always implicitly hoisted by the JavaScript interpreter to the top of the scope that contains them. The following article mainly introduces you to the relevant information about Hoisting (variable hoisting and function declaration hoisting) in JavaScript. Friends in need can refer to it. Let’s take a look together.

This article mainly introduces to you the relevant content about Hoisting (variable hoisting and function declaration hoisting) in JavaScript, and shares it for your reference and study. I won’t say much below, let’s take a look at the detailed introduction. .

How to "move" function declarations/variables to the top of the scope.

The term Hoisting is used in many JavaScript blog posts to explain identifier parsing. In fact, the word Hoisting is used to explain how variable and function declarations are hoisted to the top of the function or global scope. You won't find this term in any JavaScript documentation, and what we call Hoisting is just using its literal meaning as a metaphor.

If you already have a basic understanding of how JavaScript scoping works, a deeper understanding of Hoisting can help you build a stronger foundation. (Note from Fool's Wharf: As a general concept in JavaScript, variable hoisting and function declaration hoisting are often asked during front-end development interviews, or appear in front-end development written test questions. This shows the importance of understanding Hoisting (hoisting).)

To better understand the basics, let’s review what “Hoisting” actually means. Also, a reminder, JavaScript is an interpreted language, which is different from compiled languages, which means that JS code is executed line by line.

Consider the following example:


console.log(notyetdeclared);
// 打印 'undefined'
 
var notyetdeclared = 'now it is declared';
 
hoisting();
 
function hoisting(){
 console.log(notyetdeclared);
 // 打印 'undefined'
 
 var notyetdeclared = 'declared differently';
 
 console.log(notyetdeclared);
 // 打印 'declared differently'
}
Copy after login

After analyzing the sample code above, ask a few questions:

  • Line 6, why can this function be accessed before it is declared?

  • In line 1, no error is thrown. Is it because the variable notyetdeclared does not exist at this time?

  • In line 4, notyetdeclared has been declared in the global scope. Why is it still undefined when printed in line 9?

JavaScript is very logical and all these weird problems have a clear explanation.

We explain from the top that when code is executed in JavaScript, an execution context is established. There are two main types of execution context in JavaScript - global execution context and function execution context (Fool's Pier Note: Pay special attention to the fact that execution context is different from the context we usually talk about. Execution context refers to scope, and The usual context is the value pointed to by this). Since JavaScript is based on a single-threaded execution model, only one piece of code can be executed at a time.

For our code above, the process is as shown in the figure:

The call stack of the above example code:

  • #The program starts execution from the global execution context on the stack.

  • When the hoisting() function is called, a new function execution context is pushed onto the stack, and the global execution context is suspended.

  • After hoisting() execution is completed, the hoisting() execution context is popped from the stack and the global execution context is restored.

This procedure is self-explanatory, but doesn't really explain the exceptions we see when executing the example code. While the execution context tracks the execution of code, the lexical environment tracks the mapping of identifiers to specific variables. The lexical environment is basically the internal implementation of JavaScript's scoping mechanism. Typically, a lexical environment is associated with a specific structure of JavaScript code, such as a function or a for loop block of code. Whenever a function is created, a reference to the lexical environment it was created in is passed in an internal property called [[Environment]].

All these terms cover a simple and very logical concept. Allow it to be broken down. Lexical environment is an interesting name used to keep track of variables and functions within a block of code. In addition to tracking local variables, function declarations, and parameters, each lexical environment also tracks its parent lexical environment. So the above example code will be parsed like this in the JavaScript engine. The lexical environment of the above code is as shown in the figure:

Note:

If If you have trouble understanding, please check out the following three articles:

  • In-depth understanding of scope and context in JavaScript

  • JavaScript Core Concept Scope and Closure

  • Example Analysis JavaScript Scope

To resolve an identifier in a lexical environment, the JavaScript engine will check for references to the current environment. If no reference is found, move to the external environment by using [[environment]]. This will continue until the identifier is found, or a 'not defined' error is thrown.

Basically, the execution of JavaScript code is divided into two stages. The first phase registers all variable and function declarations in the current lexical environment. Once completed, the second phase of JavaScript execution begins!

So to elaborate on the first phase: it works in two steps.

  • Scan the code in the current function declaration. Function expressions and arrow functions are skipped. For each discovered function, a new function is created and bound to the environment using the function name. If the identifier's name already exists, its value will be overwritten.

  • Then scan the variables of the current environment. Find variables defined using var and variables placed outside other functions, and register an identifier whose value is initialized to undefined . If the identifier is present, the value will remain unchanged.

Note: Block variables defined using let and const are slightly different from var. Learn more about this in another article.

Now you should have a certain understanding of the basic concept of lexical environment, so let's go back to the sample code and explain these issues.

When setting the global context, the environment is scanned and the hoisting() function is attached to the identifier. Then in the next step, the variable notyetdeclared is registered and its value is initialized to undefined . Follow this step to continue understanding the code.

Now let’s explain the 3 questions raised in the sample code:

Line 6, why can the function be declared before access?

In phase 1, the hoisting() function has been registered in the identifier. When the JS code starts executing in the global execution context of phase 2, it will look for the lexical environment of hoisting and The function is found before its definition.

In line 1, no error is thrown. Is it because the variable notyetdeclared does not exist at this time?

Similarly, notyetdeclared is registered to the identifier and initialized to undefined in phase 1, so no error will be thrown.

Finally,

In line 4, notyetdeclared has been declared in the global scope. Why is it still undefined when printed in line 9?

Now we enter the function hoisting environment. In phase 1, notyetdeclared is registered and initialized to undefined because notyetdeclared's variables have not yet been registered in this lexical environment. The situation would be different if line 12 did not contain the var keyword.

Hopefully it is now clear that Hoisting in JavaScript is just a perspective we use to explain the principles behind it. Technically speaking, functions and variables do not move anywhere.

Summarize

The above is the detailed content of Detailed explanation of Hoisting in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles