JS variable promotion and function promotion

Source: Internet
Author: User

Before Es6, the JS language did not have block scope, that is, the scope of {}, only the global scope and function scope, so-called Ascension, that is, the declaration of the variable or function declaration promoted, for example

Console.log (global); Undefinedvar global = 111;console.log (global);//111

Obviously, the above code is in a global scope, using VAR to declare a global variable in that scope, and the actual declaration process is as follows:

var global;console.log (global); Undefinedglobal = 111;console.log (global)//111

It can be seen that the variable declaration of VAR global is promoted to the first line, so the output in the second row is shown as undefined, and the third row is assigned to the global variable;

Therefore, it is important to note that:

1, the declaration of the variable in the scope, will be promoted to the highest level of the function declaration;

2, the need to distinguish between the declaration of variables and the assignment of variables is two different behavior, need to be treated separately;

function Promotion:

There are two ways to create common functions:

1, function declaration;

function func () {  ...  }

  

2. Function expression

var func = function () {}

However, only the first function is declared in a way that functions are promoted.

As an example:

Console.log (func ());//1function func () {  return 1;      }

That is, even if the function is defined after the console, it is raised to the top of the scope, and is higher than the variable promotion.

JS variable promotion and function promotion

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.