search
HomeWeb Front-endJS TutorialJavaScript Scoping and Hoisting Translation_javascript skills

Do you know what value the alert will output after the following JavaScript code is executed?

Copy code The code is as follows:

var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();

If the answer "10" surprises you, then this may confuse you even more:
[/code]
var a = 1;
function b() {
a = 10 ;
return;
function a() {}
}
b();
alert(a);
[/code]
The browser will alert "1 ". So, what happened? Although this may seem a little strange, a little dangerous, and a little confusing, it's actually a powerful expressive feature of the language. I don't know if there is a standard that defines this behavior, but I like to use "hoisting" to describe it. This article tries to explain this mechanism, but first, let’s do some necessary understanding of JavaScript scoping.
Scoping in JavaScript
Scoping is one of the most confusing parts for JavaScript newbies. In fact, not just newbies, I've met many experienced JavaScript programmers who can't fully understand scoping. The reason JavaScript scoping is so complex is that it looks very much like a member of the C family of languages. Please look at the following C program:
Copy the code The code is as follows:

#include
int main() {
int x = 1;
printf("%d, ", x); // 1
if (1) {
int x = 2;
printf("%d, ", x); // 2
}
printf("%dn", x); // 1
}

The output of this program is 1,2,1. This is because there is a block-level scope in C-series languages. When entering a block, just like an if statement, new variables will be declared in this block-level scope. These variables will not affect outer scope. But this is not the case with JavaScript. Try the following code in Firebug:
Copy the code The code is as follows:

var x = 1;
console.log(x); // 1
if (true) {
var x = 2;
console.log(x); // 2
}
console.log(x);// 2

In this code, Firebug displays 1, 2, 2. This is because JavaScript has function-level scope. This is completely different from C-based languages. Blocks, like if statements, do not create a new scope. Only functions create new scopes.
For most programmers familiar with C, C#, C# or Java, this is unexpected and unwelcome. Fortunately, because of the flexibility of JavaScript functions, we have a solution to this problem. If you must create a temporary scope in a function, do it like this:
Copy the code The code is as follows:

function foo() {
var x = 1;
if (x) {
(function () {
var x = 2;
// some other code
}());
}
// x is still 1.
}

This aspect is indeed very flexible, it can be used to create any A place of temporary scope, not just within a block. However, I strongly recommend that you take the time to understand JavaScript scoping. It's really powerful, and it's one of my favorite features of the language. If you understand scoping well, it will be easier to understand hoisting.
Declarations, Names, and Hoisting
In JavaScript, there are four types of names in a scope:
1. Language-defined: all functions The field will contain this and arguments by default.
2. Formal parameters: Function parameters with names will enter the scope of the function body.
3. Function decalrations: in the form of function foo() {}.
4. Variable declarations: in the form of var foo;.
Function declarations and variable declarations are always implicitly hoisted by the JavaScript interpreter to the top of the scope that contains them. Obviously, the language's own definition and function parameters are already at the top of the scope. This is like the following code:
Copy the code The code is as follows:

function foo() {
bar();
var x = 1;
}

is actually interpreted like this:
Copy code The code is as follows:

function foo() {
var x;
bar();
x = 1;
}

The result is that it has no effect whether the statement is executed or not. The following two pieces of code are equivalent:
Copy the code The code is as follows:

function foo () {
if (false) {
var x = 1;
}
return;
var y = 1;
}
function foo() {
var x, y;
if (false) {
x = 1;
}
return;
y = 1;
}

Notice that the assignment part of the declaration is not hoisted. Only the declared name is promoted. This is different from function declarations, where the entire function body is also hoisted. But remember, there are generally two ways to declare a function. Consider the following JavaScript code:
Copy the code The code is as follows:

function test() {
foo(); // TypeError "foo is not a function"
bar(); // "this will run!"
var foo = function () { // Function expression is assigned to a variable 'foo'
alert("this won't run!");
}
function bar() { // Function declaration named 'bar'
alert("this will run! ");
}
}
test();

Here, only the function declaration will be promoted together with the function body, while the function expression will only be promoted The name and function body will only be assigned when the assignment statement is executed.
The above covers all the basics of hoisting. It doesn’t seem that complicated or confusing, right? However, this is JavaScript, and there are always going to be a little complications in some special cases.
Name Resolution Order
The most important special case to remember is the name resolution order. Remember that there are four ways for a name to enter a scope. The order I listed above is the order in which they parse. In general, if a name is already defined, it will never be overwritten by another name with the same name that has different attributes. This means that function declarations have higher priority than variable declarations. But this does not mean that the assignment to this name is invalid, it is just that the declared part will be ignored. There are a few exceptions:
The built-in name arguments behave a little weirdly. It seems to be declared after the formal parameters and before the function declaration. This means that the formal parameter named arguments will have higher priority than the built-in arguments, even if the parameter is undefined. This is a bad feature, do not use arguments as formal parameters.
Any attempt to use this as an identifier will cause a syntax error, which is a good feature.
If there are multiple formal parameters with the same name, the parameter at the end of the list has the highest priority, even if it is undefined.
Name Function Expressions
You can define a name for a function in a function expression, just like a function declaration statement. But this does not make it a function declaration, and the name is not introduced into the scope, and the function body is not hoisted. Here's some code to illustrate what I mean:
Copy code Here's the code:

foo(); // TypeError "foo is not a function"
bar(); // valid
baz(); // TypeError "baz is not a function"
spam(); / / ReferenceError "spam is not defined"
var foo = function () {}; // Anonymous function expression ('foo' is promoted)
function bar() {}; // Function declaration ('bar ' and the function body are promoted)
var baz = function spam() {}; // Named function expression (only 'baz' is promoted)
foo(); // valid
bar() ; // valid
baz(); // valid
spam(); // ReferenceError "spam is not defined"

How to Code With This Knowledge
Now you Now that you understand scoping and hoisting, what does this mean for writing JavaScript code? The most important one is to always use the var statement when declaring variables. I strongly recommend that you only use one var at the top of each scope. If you force yourself to do this, you will never be troubled by promotion-related problems. Although doing so makes it more difficult to keep track of which variables are actually declared in the current scope. I recommend using the onevar option in JSLint. If you do all the previous suggestions, your code will look like this:
Copy the codeThe code will look like this:

/*jslint onevar: true [...] */
function foo(a, b, c) {
var x = 1,
bar,
baz = "something";
}

What the Standard Says
I find it always useful to refer directly to the ECMAScript Standard (pdf) to understand how these things work it works. The following is an excerpt about variable declaration and scope (section 12.2.2):
If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, as described in section 10.1.3 . Otherwise, they are defined with global scope (that is, they are created as members of the global object, as described in section 10.1.3) using property attributes { DontDelete }. Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.

I hope this article can shed some light on the most confusing part of JavaScript programmers. I tried my best to write it comprehensively so as not to cause more confusion. If I made a mistake or missed something important, please let me know.
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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment