JavaScript variable Declaration is very simple, but here there are also knowledge points to learn, it is very important for basic JavaScript learning. After lunch last Thursday, leader sent us a JavaScript question. Our Team has front-end, back-end, and mobile web, therefore, you may have different understandings of the question, and then discuss the question in the QQ discussion group. I found that although it was very basic, I learned a lot from the discussion and shared it. Of course, in the view of developers with development experience, these are the most basic things to learn JavaScript. Because jQuery or third JS components are usually used, you do not pay enough attention to basic JavaScript learning. The question is as follows: what results are output by alert twice?
The Code is as follows:
Type = "text/javascript">
Var a = 1;
Var;
Alert (typeof );
(Function (){
B = '-----';
Var B;
})();
Alert (typeof B );
Script
My answer is: 1. undefined 2. undefined. Then, let's take a closer look at the answer to the question. My analysis of the question:
1. Declare a and assign a value to 1, and then re-declare a, but no value is assigned at this time, the default value of the variable should be undefined.
2. The B variable is a local variable in the function, and the alert output the global variable B, so it is undefiend.
I run the code in Chrome. The correct result is 1. number 2. undefined. This section describes the advance concept of JavaScript variable declaration.
Let's look at another example, for example:
The Code is as follows:
Test ();
Function test (){
Alert ("Hello World! ");
}
The program will not report an error, but the running result is: Hello World !. Principle: Before executing a statement, the computer searches for all function definitions and then saves the related functions.
Question 1st:
Var a = 1;
Var;
The declaration of variable a in Row 3 is equivalent to declaring a at the top. Then, the first sentence is to re-declare a and assign a value to 1. So typeof a is number
Question 2nd:
B = '-----';
Var B;
Second question: B = '-----', the program first checks whether the context has the declaration of variable B. If so, the value is '-----'. But alert (typeof B); is the global variable B output outside the function, all are undefined.
Note: The assignment of variables is not performed in advance.
See the following code snippet:
The Code is as follows: