JavaScript Variable declaration predecessor

Source: Internet
Author: User

Variable declaration predecessor:

The so-called variable declaration predecessor is in a scope block, all the variables are placed in the beginning of the block declaration, the following example you can understand

1 var a = 1; 2 function Main () {3     Console.log (a);   14}5 main (); // Output 1

The above code outputs the value of the outer variable A.

1 var a = 1; 2 function Main () {3    Console.log (a); 4     var a = 2; 5 }6 Main ()// output undefined

What do you want to do to output undefined? This is because the script automatically declares the variable declaration before it executes, parsing it as follows:

1 var a = 1; 2 function Main () {3     var A; 4     Console.log (a); 5     A = 2; 6 }

So the output is undefined.

Summary:

For the above problem, we should try to put the variable declaration at the beginning of the scope when we write the JavaScript script, so we can avoid the above problem.

Sometimes we encounter some puzzling problems in the development, in fact, some of us do not understand the implementation principle of JavaScript caused, only to understand, we can reduce such errors, hope this article can help you!

JavaScript Variable declaration predecessor

Related Article

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.