Local variables and global variables in JS

Source: Internet
Author: User

In JavaScript, variables have the same scopes as those in other programming languages: local variables and global variables.

The following example shows the relationship between local variables and global variables:

Instance 1:

VaR MSG = "global variable"; function show () {MSG = "local variable"; document. writeln (MSG) ;}show (); document. writeln (MSG );

The final execution result is:

Local variable

Local variable

 

Example 2:

VaR MSG = "global variable"; function show () {var MSG; MSG = "local variable"; document. writeln (MSG);} Show (); document. writeln (MSG );

The final execution result is:

Local variable

Global Variables

 

Analysis: it is not difficult to understand that calling the show () function will print "local variables". The show () function in the instance operates on the global variable MSG, when show () at the end of the function, the local variable MSG has been changed to another value, so the "local variable" is printed, and the show () A new local variable MSG is defined in the function, and its local variable is also operated (the global variable MSG is overwritten). When the show () function ends, the remaining Code does not have a half-cent relationship with the show () function, so the "global variable" is printed ".

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.