In-depth understanding of scope and variable promotion (hoisting) in JS

Source: Internet
Author: User
Tags variable scope

Scope (scoping)

The JavaScript scope is confusing because its program syntax itself is long like the C-family language. My understanding of scopes is a closed space that only has an effect on a range and does not have an impact on the outside. In some of these spaces, external variables cannot be accessed externally, but external variables can be accessed internally.

C language variables are divided into global variables and local variables, the scope of global variables is any file and function access (of course, for non-variable definition of other C files, you need to use the extern keyword to declare, using the static keyword can also be scoped to the current file), The scope of a local variable is the block-level scope covered by the declaration to the nearest curly brace. Java has no global variables, there are class variables, member variables and local variables, the scope of action according to Public,protected,private and other access rights have different scopes, here is not more.

What are the JS scopes?

In ES5, JS has only two forms of scope: global scope and function scope.

The global scope is actually the scope of the global object and can be accessed anywhere (if not overridden by a function scope).

A function object scope is different from the local variable scope of C, and its scope is the entire function range, whether it is declared anywhere in the function! This is called hoisting, which is the concept of variable ascension. But in no hurry, the following will be specifically for hoisting to explain.

However, in ES6, a new block-level scope (the scope of the most recent curly braces) is added, but only the variables declared by the Let mode are included.
Scope Demo:

When you define a variable, if you do not write Var, such as i=0, it is defined as a global variable, scoped to a global scope, otherwise a local variable, scoped to a function scope. The first line of the Var i=0, the reason is that it is a global variable, because it is already declared in the global zone, not within the scope of the function, so it is the same as i=0.

As for, why the results will be so, continue to look down on the know.

Declaration Form

Variable declaration:

function declaration:

Variable lift (hoisting)

Raises a question

What does the following code output?

Most beginners of this question say that the output is a date. But the real result is undefined. Why is that so? Here is a concept--hoisting, the Chinese meaning is the variable promotion. The explanation for variable hoisting in MDN is this:

var hoisting

Because variable declarations (and declarations in general) be processed before any code is executed, declaring a variabl e anywhere in the code was equivalent to declaring it at the top. This also means, a variable can appear to be used before it ' s declared. This behavior is called "hoisting", as it appears, the variable declaration are moved to the top of the function or Glo Bal code.

This passage is translated down

Because variable declarations are processed before arbitrary code executes, declaring variables anywhere in the code area is the same as declaring them at the very beginning (top). In other words, it looks like a variable can be used before the declaration! This behavior is called "hoisting", which is the variable elevation, which looks like the declaration of a variable is automatically moved to the top of the function or global code.

Note: the definition is not promoted because it is merely a declaration of Ascension.

So, the above code is actually the following form:

Therefore, it should be understood that when the console output, the TMP variable is only declared but not defined, so the output should be undefined.

It is necessary to note that although all declarations (including ES5 Var, function, and ES6 function *, let, const, Class) are promoted, VAR, function, function * and let, const, Class's ascension is not the same! The specific reasons can be seen here (in general, although Let,const,class is also promoted, but it is not initialized, at this time to visit them will be reported Referenceerror exception, they need to be executed when the statement will be initialized, The state before being initialized is called the temporal dead Zone). Let's look at a piece of code and we'll know:


Here A is promoted, but because the definition is behind, so the output undefined

A although it was promoted here, but it quoted a mistake!

Why or so

For this reason, it is recommended that when declaring variables, the variables used are written at the top of the scope (global scope or function scope), so that the code looks clearer and easier to see that the variable is from the scope of the function and which is from the scope chain (this article does not explain this much, Please read the reader's own Baidu, have the opportunity to add a note).

Duplicate declaration

The above output is actually: 1 2 2. Although it appears that the X is declared two times, but it said that JS var variable only global scope and function scope two, and the declaration will be promoted, so in fact, X will be declared at the top of the first place, VAR x=2 declaration will be ignored, only for assignment. This means that the above code is actually consistent with the following.

Problems with functions and variables being raised at the same time

What happens if the function and the variable type are both declared and defined? Look at the code below.


A

The above output is actually: function foo(){}  , that is, the function content.

And if that's the way it is?


B

Its output has become: undefined

Why is that?

The original function promotion is divided into two situations:

One: function declaration. It's a, function foo(){} this form.

Another type: function expression. It's the top B, var foo=function(){} this form.

The second form is actually the declaration definition of the VAR variable, so the result of the above B output is undefined should be able to understand.

The form of the first function declaration, when promoted, is lifted throughout, including the part of the function definition! So a is equivalent to the following way!

The reason is because: 1, the function declaration is promoted to the topmost, 2, affirms only once, therefore var foo=‘i am text‘ the subsequent declaration will be ignored.

And the precedence of the function declaration is better than the variable declaration, so the output of the following form is also the function content:

Summarize

To thoroughly understand the scope and hoisting of JS, just remember the following three points:

1. All declarations will be promoted to the top of the scope

2, the same variable declaration is only made once, and therefore other declarations will be ignored

3, the function declaration priority is superior to the variable declaration, and the function declaration will be promoted together with the definition

Attention:

With the WITH statement, you can temporarily change the scope chain of a run-time context, where a variable defined by a non-VAR is accessed, and the property of the object in with is accessed first, and then the property is checked upward along the scope chain.

In-depth understanding of scope and variable promotion (hoisting) in JS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.