Understanding of JavaScript variable promotion and function promotion

Source: Internet
Author: User

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

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.