When writing JavaScript code, you often encounter strange problems, such as:
Console.log (typeof hello); var hello = 123; //variable function Hello () {//function declaration}console.log (typeof Hello); var function () {//function expression}console.log (typeof Hello);
For why this is the result: function number function A lot of people may be holding a skeptical attitude, why not undefined function function?
In the above code, the concept of variable elevation and function promotion is actually involved, in the JavaScript engine, the parsing of JavaScript code is not parsed from top to bottom, line by row, but by code block:
In the same scope, the first is to raise the declaration function to the top of the code, followed by the variable promotion, and finally the function expression, the above code in the JavaScript engine parsing can be seen as follows:
function Hello () {//Functions declaration }
var Hello;
Hello = 123;
Console.log (typeof hello);//number
var Hello;
Hello = function () {}
Console.log (typeof hello);//function
var hello = 123; The parse is to define the variable hello first, var hello, and then assign a value to the variable, where the var Hello is a promotion of the variable. Such as:
Console.log (typeof hello);//undefined
var hello = 123;
Console.log (typeof hello);//number
The variable hello here is declared to the top of the scope
The common examples are:
var hello = 123;
function Test () {
Console.log (hello);//undefined
var hello = ' haha ';
Console.log (hello);//haha
}
Test ();
Console.log (hello);//123
undefined haha 123
In the scope of the test function, the first console.log (hello), because the Hello variable is promoted, is undefined, the second console.log (hello), and the print is haha
The end result is undefined haha 123
Understanding of JavaScript variable promotion and function promotion