The easy mixing point of local variables and global variables in JS

Source: Internet
Author: User

1. The following outputs are:

Undefined
Local variables

<script type= "Application/javascript" >
var scope= "global variable";
Function cal () {
Document.writeln (scope+ "<br/>");
var scope= "local variables"; (1) Office
Document.writeln (scope+ "<br/>");
}
Cal ();
</script>

2. If the above is not understood, it is easy to understand that the scope of the function is changed to Scope1.

Cause: The variable in the function is a local variable, and the entire scope is within the function. Here is the main definition of variables with Var and not the difference between var.

That is: 1) If you use Var, the program will force a new variable to be defined

2) If not used, the system takes precedence over whether the variable exists in the current context (not just above, but also below) . The system is redefined only if the variable does not exist.

Therefore, the scope defined below is found in 1, but is not assigned at (1), so the undefined is displayed.

The easy mixing point of local variables and global variables in JS

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.