JavaScript Variables
Variable
A variable
is a “container” for information you want to store. A variable’s value can
change during the script. You can refer to a variable by name to see its value
or to change its value.
Rules for
variable names:
·
Variable names are case sensitive.
·
They must begin with a letter or the underscore
character
IMPORTANT! JavaScript is
case-sensitive! A variable named strname is not the same as a variable named
STRNAME!
Variable
are used to store data. This example will show you how
Example:
<html>
<body>
<script
type=”text/javascript”>
var name = “Ram”
document.write(name)
document.write(“<h1>”+name+”</h1>”)
</script>
<p>This example declares a
variable, assigns a valuate to it, and then displays the variable. </p>
<p>Then the variable is
displayed one more time, only this time as a heading.</p>
</body>
</html>
Declare Variable
You can create a variable with the var statement:
Var strname=some value
You can also create a variable without the var statement:
Strname = some value
Assign a Value to a Variable
You can assign a value to a variable like this:
Var strname = “Ram”
Or like this:
Strname = “Ram”
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable “strname” has the value “Hege”
Lifetime of Variables
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 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 lifetime of these variables starts when they are declared, and
ends when the page is closed.