|
|
JavaScript variablesWe know the importance of JavaScript variables. We will learn some of the basic things here.
Note that JavaScript variables are case sensitive. To check the variables we can use different functions like typeof, parseInt, parseFloat etc. Let us start with some basic requirements of a 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"
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 global variable inside the function. So local variables of 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>
Accessing variables of Parent window
We can read the variables of parent window and display ( or use ) in child window after opening. Here is the code for parent window.
<html>
<head>
<title></title>
<script type="text/javascript">
my_var="Hello World";
document.write(my_var)
</script>
</head>
<body>
<a href="javascript:void(0);" NAME="My Window Name" onClick=window.open("variable2.htm","rating","width=550,height=170,left=150, top=200,toolbar=1,status=1");>Click here to open the child window</a>
</body>
</html>
Now the child window code ( variable2.htm)
<script type="text/javascript">
document.write(opener.my_var)
</script>
typeof: Checking the type of variable
We can print the type of variable by using typeof function. Here is an example.
my_var="Hello World";
document.write(typeof(my_var))
Output of above code is string. Similarly based the type of variable, we will get outputs as
string, number,boolean,object etc.
| |
| |
|
|
|
|
|