Home >Web Front-end >JS Tutorial >Detailed explanation of variable promotion and function promotion in js
This article brings you an article on variable promotion and function promotion based on js (detailed explanation). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look, I hope it can help everyone.
1. Variable promotion
Before ES6, JavaScript did not have block-level scope (a pair of curly braces {} is a block-level scope), only global scope and function scope. Variable hoisting hoists a variable declaration to the beginning of its scope.
The example of the previous resume is:
console.log(global); // undefined var global = 'global'; console.log(global); // global function fn () { console.log(a); // undefined var a = 'aaa'; console.log(a); // aaa } fn();
The reason why the above print result is due to the variable promotion of js, in fact, the above code It is executed as follows:
var global; // 变量提升,全局作用域范围内,此时只是声明,并没有赋值 console.log(global); // undefined global = 'global'; // 此时才赋值 console.log(global); // 打印出global function fn () { var a; // 变量提升,函数作用域范围内 console.log(a); a = 'aaa'; console.log(a); } fn();
2. Function improvement
The functions created in js are Two ways: function declaration and function literal. Function hoisting only exists for function declarations! For example:
console.log(f1); // function f1() {} console.log(f2); // undefined function f1() {} var f2 = function() {}
The reason why there are the above printing results is because the function promotion in js causes the code to actually be executed as follows:
function f1() {} // 函数提升,整个代码块提升到文件的最开始<br>console.log(f1); console.log(f2); var f2 = function() {}
Conclusion: That’s basically it. If you want to master it proficiently, you can do more exercises. test:
console.log(f1()); console.log(f2); function f1() {console.log('aa')} var f2 = function() {}
(function() { console.log(a); a = 'aaa'; var a = 'bbb'; console.log(a); })();
Related recommendations:
Detailed explanation of javascript variable promotion
Detailed explanation of js variable promotion and function declaration pre-parsing examples
In-depth understanding of scope and variable hoisting in JS
The above is the detailed content of Detailed explanation of variable promotion and function promotion in js. For more information, please follow other related articles on the PHP Chinese website!