Home  >  Article  >  Web Front-end  >  Detailed explanation of Hoisting in JavaScript

Detailed explanation of Hoisting in JavaScript

黄舟
黄舟Original
2017-08-20 10:10:132286browse

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'
}

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:
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