A variable is simply a container that stores a value in a location. This value can be changed during the execution of the program. There are two types of variable.
- Local Variable:- A variable is declared within the function or inside the block. It is accessible within the function or block only.
<script>
function abc()
{
variable x = 10:// local variable
}
</script> - Global Variable:– A variable is declared outside of any function or declared with a window object.
<script>
var data = 200://global variable
function a () {
}
</script>
Rules for declaring a variable name
- The name must start with a letter ( a to z or A to Z), underscore (_), or dollar sign ($)
- After the first letter, we can use digits (0 to 9)
- Variables are case-sensitive (ex:- harry and Harry are different)
- White space not allowed (ex:- int code with Harry; is invalid)
- let can be updated but not re-declared
- Constant can neither be updated nor be re-declared.
- Variables are initialized with undefined whereas let and constant variables are not initialized.