Introduction:
Variables are used to store the value. Once a variable is declared, it may be accessed anywhere inside the function where it is declared. Variables declared outside any function. Variables can be declared with a var statement.
Example: In this example you will learn how to declare the variables.
var myname="puru";
document.write(myname);
Here variable name is declared in left side of the expression and assign the value in the right side of the expression.
Example: I am giving another example to understand the variable declaration.
<html>
<head><title>Variable declaration</title>
</head>
<body>
<script type="text/javascript">
var name = "Charls"
document.write(name)
document.write("<h1>"+name+"</h1>")
</script>
<p><font color= olive> you are looking the value of variable as Charls.</font>
</p>
<p><font color= olive>The variable is displayed one more time, only this time as a heading.</font>
</p>
</body>
</html>
Output:
We can declare more than one variable at once using the var keyword, each variable name is separated by comma.
For Example: If we want to declare two variables as myName and myAddress then we will declare like this:
<script type="text/javascript">
var myName;
var myAddress;
</script>
We can also declare on one line like this:
<script type="text/javascript">
var myName,myAddress;
</script>
Scope of the variable:
When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables.
You can have local variables with the same name in different functions, because each variable is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it. The scope of these variables starts when they are declared, and ends when the page is closed. These variables are called global variables.
We can declare the variable as globally without using var statement.
For Example:
<script type="text/javascript">
x=20; // x is aglobal variable.
var name=Puru; // global variable
fun hi()
{
var y=By;//local variable
p=10; //global variable because it is declare without 'var'statement.
return x;
}
</script>