Variable declaration in JavaScript is earlier than value assignment Analysis

Source: Internet
Author: User

As follows:
Copy codeCode: var a = 3;

There are two steps:
1. initialize a as undefined.
2 a value 3

So there will be some "Incredible" phenomenon, that is, the variables in JS can be used first and then declared. This is not allowed in Java.

Copy codeThe Code is as follows: System. out. println ();
Int a = 1;

Compilation and translation fail. But JS can, as shown below:
Copy codeThe Code is as follows: alert ();
Var;

Although it is undefined, no error is reported. It indicates that a is indeed declared and is undefined.

If it is just "alert (a)" and there is no "var a", the JS engine will report an error.
Copy codeThe Code is as follows: alert ();

FF is as follows:

Although it can be used before Declaration, this will cause loss of the effect of the assignment. As follows:
Copy codeThe Code is as follows:
Alert ();
Var a = 1;


The output is still undefined rather than 1.

Another example,
Copy codeThe Code is as follows:
Alert ('A' in window); // true
Var;

Although the Code form is written in alert, the engine automatically processes the declaration of var. The final output is true.

It is not difficult to understand the running results of the following code.
Copy codeThe Code is as follows:
If (! ("A" in window )){
Var a = 1;
}
Alert ();

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.