Variable declarations in JavaScript are older than assignment analysis _javascript tips

Source: Internet
Author: User
As follows
Copy Code code as follows:
var a = 3;


There are actually two steps:
1 Initialize A to undefined
2 A assigned value 3

So there will be some "strange" phenomenon, that is, JS variables can be used first after the declaration. This is not allowed in Java.

Copy Code code as follows:
System.out.println (a);
int a = 1;

compilation does not pass. But JS can, as follows
Copy Code code as follows:
alert (a);
var A;

Although it is undefined, it will not be an error. Note A does declare, and it is undefined.

If only "alert (a)", there is no "var a", the JS engine will complain.
Copy Code code as follows:
alert (a);


FF in the following

Although you can use the declaration first, this will result in the loss of the assignment. As follows

Copy Code code as follows:

alert (a);
var a = 1;


The output is still undefined rather than 1.

Another example,
Copy Code code as follows:

Alert (' A ' in window); True
var A;

Although the code form is written on alert, the engine will still automatically process the declaration of VAR first. The last output is true.

It's not hard to understand this. The following code runs the result
Copy Code code as follows:

if (! () A "in Window") {
var a = 1;
}
alert (a);

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.