Home >Web Front-end >JS Tutorial >A brief analysis of the variable declaration hoisting problem in JavaScript (Hoisting)

A brief analysis of the variable declaration hoisting problem in JavaScript (Hoisting)

高洛峰
高洛峰Original
2016-12-03 13:45:331245browse

1. Variable declaration hoisting

hoisting English ['hɔɪstɪŋ] US ['hɔɪstɪŋ]

n. Lifting, lifting

v. Hoisting, raising (present participle of hoist)

First Let’s look at a chestnut

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

Here will output undefined, 'world', 'hello'

There are two main knowledge points here:

1. Scope

2. Variable declaration improvement

JavaScript is an interpreted language. When the code is executed in an interpreter (such as Chrome's V8 engine) environment, there will be a pre-parsing process. At this time, variable declarations and function declarations will be promoted to the current scope. At the forefront, this behavior is called declaration hoisting (Hoisting)

Let’s look at the above example again. This code has two levels of scope, the global scope and the function foo scope, and the variable declaration in foo is in the pre-parsing process will be promoted to the front of the function scope, so the code will become like this:

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

When the first log is executed, the variable cc is only declared and not assigned, so the printed is undefined

2. Function declaration promotion

There are two ways to declare a function: function declaration and function expression

// 函数声明
function foo(a, b) {
 return a + b;
}
// 函数表达式
var foo = function(a, b) {
 return a + b;
}

When the parser loads data into the execution environment, the function declaration and function expression Styles are not created equal. The parser will first read the function declaration and make it available (accessible) before executing any code; as for the function expression, it will not be actually interpreted and executed until the parser reaches the line of code where it is located.

Of course, you can also use function declaration and function expression at the same time, such as var a = function b(){}. The result is that it only has the effect of function expression, and b will be automatically ignored, so only the variable promotion effect will occur. .


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