Home > Web Front-end > JS Tutorial > Variable declaration in JavaScript precedes assignment analysis_javascript tips

Variable declaration in JavaScript precedes assignment analysis_javascript tips

WBOY
Release: 2016-05-16 17:55:47
Original
1048 people have browsed it

As follows

Copy code The code is as follows:
var a = 3;


There are actually two steps:
1 Initialize a to undefined
2 Assign a value 3

Therefore, there will be some "unbelievable" phenomena, that is, variables in JS can be used first and then declared. This is not allowed in Java.

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

Compilation fails. But JS can, as follows
Copy code The code is as follows:
alert(a);
var a ;

Although it is undefined, no error will be reported. It shows that a is indeed declared and is undefined.

If it is just "alert(a)" without "var a", the JS engine will report an error.
Copy code The code is as follows:
alert(a);


FF as follows

Although you can use it first and then declare it, this will cause the effect of the assignment to be lost. As follows

Copy the code The code is as follows:

alert(a);
var a = 1;


This time the output is still undefined instead of 1.

Another example,
Copy code The code is as follows:

alert(' a' in window); // true
var a;

Although the code is formally written after alert, the engine still automatically processes the var declaration first. The final output is true.

After understanding this, it is not difficult to understand the results of the following code
Copy the code The code is as follows:

if (!("a" in window)) {
var a = 1;
}
alert(a);
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template