JS Small tips of variable declaration in advance

Source: Internet
Author: User

To discuss the advance of variable declarations only:

Understand this code:

var name = "AAA"; function Test () {    alert (typeof  name);     var name = "BBB";    Alert (typeof  name);} Test ();

-Answer: Undefined, string

Analysis

1, two principles: A, JS in the declaration of variables in advance; B, the scope of JS and the way to search for variables

2, the first time to execute "typeof name", the first will be in the scope of the function to query whether the name exists. Because of the advance of the variable declaration, the declaration of name in the local scope was advanced, but was not assigned a value, so it is undefined.

3, the second time better understanding, is a string.

4, because the name has been found in the local scope, so it does not need to be found in the global scope, so two times the name is considered in the local scope. You can see the description of the scope in the fourth chapter of Advanced JavaScript programming, and focus on the process of JS's search for variables along the scope. As follows:

5, notice that sometimes the browser will have some default operation, this time needs to be specific analysis.

Practice Code

var x = 1; function test2 (x) {    alert (x);     var x = 2;    alert (x);} function test3 () {    alert (x);     var x = 3;    alert (x);} Test2 (x); Test3 ();

-Answer: 1,2;undefined,3;

JS Small tips of variable declaration in advance

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.