JavaScript variables are case sensitive. To check the variables we can use different functions like typeof, parseInt, parseFloat etc.
Basic requirements of declaring a variable.
Our JavaScript variables are case sensitive, so we can use lower or upper case letters
We can use digits from 0 to 9
We can use underscore _ and ampersand & in our variable
Space and punctuation characters are not allowed
First character of the variable has to be underscore or alphabet
No reserve words or keywords to be used as variable.
Declaring a JavaScript variable.
We can simply assign the value to the variable like this
my_var="Hello World"
Or we can exclusively declare and assign the value by using var
var my_var="Hello World"
Examples:
var 2my_var='test' // Wrong , variable can't start with 2
var for='test' // Wrong, for is a reserve word
Local & global variable
This is a good practice to use var to declare a variable. Any variable we declare in our main script will be available as a global variable inside the function. So local variables of the same name inside a function must be declared if they are to be used separately. Here is an example of variables used inside and outside the function.
<script type="text/javascript">
function my_function(){
var my_var=" New value "
document.write("Inside function " + my_var)
}
my_var="Hello World";
document.write(my_var)
my_function();
</script>