Scope of the JS variable

Source: Internet
Author: User


The scope of a variable refers to the range of variables. That is, the variable is valid only for a specific range, beyond which the range is invalid.

In JavaScript, there are two variables, global variables, and local variables:

    • Global Variables : can be called anywhere in the script, where the scope of the global variable is the entire script area in the current document.
    • Local Variables : can only be used inside the function where the variable declaration statement belongs, the scope of the local variable is only the body of the function.


When declaring a variable, decide whether to declare the variable as a global variable or a local variable, depending on the purpose of the program. In general, variables that hold global information (such as user information, menu options, and so on) are declared as global variables, while variables that hold temporary information, such as the format string to be exported, the middle variable of a mathematical operation, and so on, are declared as local variables.

Illustrate variable scopes

"Example 2-1" examines the following code:

  1. >
  2. >
  3. <title> Local variables and global variables </title>
  4. >
  5. <body>
  6. <script type="Text/javascript">
  7. var total=+; //global variable
  8. function add(num){
  9. var total; //Local variables
  10. Total=2*num;
  11. return total;
  12. }
  13. </script>
  14. <p onclick="alert (Add (100));" > Show Local Variables </p>
  15. <p onclick="alert (total);" > Show global Variables </p>
  16. </body>
  17. >

Save and run the code, click the first paragraph of text, display 200, click the second paragraph of text, display 100.

Analysis: Click the first paragraph of text, run the Add () function, assign a value to the total variable. At this point, JavaScript looks for the total variable, and if it is found inside the function, it is assigned, and is found outside the function. Obviously, it has been found inside the function, and its value is 200 after the assignment. The total variable here is a local variable.

When you click the second paragraph of text, JavaScript looks for the total variable in the global, returns its value if found, and throws an error if it is not found. Obviously, it has been found, and its value is 100. The total variable here is the global variable.

It can be found that assigning a value to the total variable inside the Add () function does not affect the external total variable.

Example 2-2 makes a slight change to "example 2-1", removing the declaration of the total variable inside the Add () function. As shown below:

  1. >
  2. >
  3. <title> Local variables and global variables </title>
  4. >
  5. <body>
  6. <script type="Text/javascript">
  7. var total=+; //global variable
  8. function add(num){
  9. Total=2*num;
  10. return total;
  11. }
  12. </script>
  13. <p onclick="alert (Add (100));" > This is not a local variable </p>
  14. <p onclick="alert (total);" > Show global Variables </p>
  15. </body>
  16. >

Save and run the code, and click two paragraphs to display 200.

The results show that JavaScript does not find the total variable inside the Add () function, and looks outside the function to find it and assign it to it, overwriting the original value.

Description: JavaScript is looking for variables from a small range to a wide range. If the corresponding variable is not found in the current scope, it will be looked up to the upper level at the first level, and when it is found, it will be manipulated, and an error would be thrown if it is not found.

Note: In any case, JavaScript will never look for a variable from a wide range to a small range. If a variable is not found outside the function, it is definitely not going to look inside the function.

Declaring a global variable inside a function

As already mentioned, the VAR keyword is used when declaring variables, but it can also be used without.

Variables declared without the VAR keyword are global variables , whether outside or inside the function.

This gives us two ways to declare global variables:

    • Use the var keyword declaration outside of the function;
    • Do not use the var keyword declaration anywhere.

Example 2-3 makes a slight change to "example 2-2", removing the declaration of the total variable outside the Add () function. As shown below:

  1. >
  2. >
  3. <title> Local variables and global variables </title>
  4. >
  5. <body>
  6. <script type="Text/javascript">
  7. function add(num){
  8. Total=2*num; //Total is a global variable
  9. return total;
  10. }
  11. </script>
  12. <p onclick="alert (Add (100));" > This is not a local variable </p>
  13. <p onclick="alert (total);" > Show global Variables </p>
  14. </body>
  15. >

Save and run the code, and click two paragraphs to display 200.

The above results indicate that the total variable declared inside the Add () function is no longer a local variable, and it is valid at the global scope.

Attention:

    • When declaring variables, use the var keyword as much as possible, which is very helpful for the program structure.
    • Try not to declare a global variable inside a function, or to declare a variable with the same name inside and outside of a function, both of which cause a variable to be confused.
Only variables declared with the VAR keyword within a function are local variables

It is important to emphasize that only variables declared using the var keyword inside a function are local variables, and declaring variables in other "statement blocks" using the var keyword is generally a global variable, if...else ... This is true for both the selection structure and the for loop structure.

Example 2-4 declares a variable inside a for loop.

  1. >
  2. >
  3. <title> Declare variables inside a for loop </title>
  4. >
  5. <body>
  6. <script type="Text/javascript">
  7. For(var i=0; I<=5; I+ +){
  8. var x=+;
  9. }
  10. </script>
  11. <p onclick="alert (i);" > Display the value of the I variable </p>
  12. <p onclick="alert (x);" > Display the value of the x variable </p>
  13. </body>
  14. >

Click the first paragraph of text, display 6, click the second paragraph of text, display 100.

The above results indicate that I and X declared inside the for loop are not local variables, but global variables.

Summary: In addition to functions, JavaScript is not block-scoped.

Scope of the JS variable

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.