JS variable Promotion Deep Understanding _ basics

Source: Internet
Author: User
Tags function definition

The function definition of JavaScript has a feature that scans the statement of the entire function body and "promotes" all declared variables to the top of the function:

' Use strict ';

function foo () {
  var x = ' Hello, ' + y;
  alert (x);
  var y = ' Bob ';
}
Foo ();

Although it is strict mode, the statement var x = ' Hello, ' + y is not an error, because the variable y is stated later. But alert shows hello, undefined, indicating that the value of variable y is undefined. This is precisely because the JavaScript engine automatically promotes the declaration of the variable y, but does not raise the assignment of the variable Y.

For the above foo () function, the JavaScript engine sees code that is equivalent to:

function foo () {
  var y;//elevation variable y declaration
  var x = ' Hello, ' + y;
  alert (x);
  y = ' Bob ';
}

Because of this weird "feature" of JavaScript, when we define variables inside a function, we strictly observe the rule "declare all variables first within a function". The most common practice is to use all the variables used internally by a VAR declaration function:

function foo () {
  var
    x = 1,//x initialized to 1
    y = x + 1,//y initialized to 2
    z, I;//z and I for undefined
  //Other statement:
  F or (i=0 i<100; i++) {
    ...
  }}
}

The above JS variable to promote in-depth understanding of the small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.