In js, variables are containers for storing information; there are two types of variables in JavaScript: local variables and global variables.
#How to declare variables in js?
In js, you can use the keyword "var" or "let" and add the "variable name" to declare a variable. [Recommended related video tutorials: JavaScript Tutorial]
The names of js variables, also called identifiers, need to follow some standards:
1. The name must start with letters ( a to z or A to Z), begin with an underscore (_) or dollar ($) sign, but it is not recommended to use an underscore (_) or dollar ($) sign at the beginning.
2. After the first letter, you can also use numbers (0 to 9), such as value1.
3. JS variables are case-sensitive. For example: x and X are different variables.
Let’s take a look at the declaration of js variables through examples:
Correct variable declaration:
var x = 10 ; var _value = "sonoo" ;
Incorrect variable declaration:
var 123 = 30 ; var * aa = 320 ;
JavaScript local variables
Variables declared within a block or function are called local variables; local variables can only be accessed within the declared block or function. The declared block or function has no effect and cannot be accessed. Example:
<div class="demo"> <p id="p1"></p> <p id="p2"></p> </div> <script type="text/javascript"> function abc(){ var x= 10 ; //局部变量 var y= 10 ; //局部变量 document.getElementById("p1").innerHTML=x; } abc(); document.getElementById("p2").innerHTML=y; </script>
Rendering:
This is because the variable x and variable y are both local variables; the variable x is in the function abc( ) is called and output internally, but variable y cannot be called and output outside function abc(), and an error will be reported:
JavaScript global variable
Variables declared outside a block or function, or declared using a window object, are called global variables. Global variables can be accessed by any function (or block) throughout the code. Example:
<div class="demo"> <p id="p1"></p> <p id="p2"></p> <p id="p3"></p> <p id="p4"></p> </div> <script type="text/javascript"> var x= "x=10" ; //局部变量 function abc(){ var y= "y=10" ; //局部变量 document.getElementById("p1").innerHTML=x; document.getElementById("p2").innerHTML=y; } abc(); document.getElementById("p3").innerHTML=x; document.getElementById("p4").innerHTML=y; </script>
Rendering:
It can be seen that the local variable y cannot be accessed and output outside the function abc(), and an error will be reported:
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of What are variables in js and what types are they. For more information, please follow other related articles on the PHP Chinese website!