|
Variables
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
Declaring Variables
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
Assigning Values to Variables
You assign a value to a variable like this:
var strname = "Hege"
Or like this:
strname = "Hege"
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".
Assignment Operators
Operator Example Result
= i = 5 i equals 5
+= i += 5 i equals i + 5
-= i -= 5 i equals i - 5
*= i *= 5 i equals i * 5
/= i /= 5 i equals i / 5
%= i %= 5 i equals i %5
++ i++ i equals i+1
-- i-- i equals i-1
Lifetime of Variables
When you declare a variable within a function, only code within
that function can access or change the value of that variable.
When the function exits, 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
in your script will recognize it. These variables exists from
the time they are declared until the time the script is finished
running.
The Boolean object
The Boolean object is one of JavaScript's built-in objects. It
can return two values: 0 for false and any other integer value
for true. It is used to return a result of a conditional test.
For example if you want some code to be executed if a condition
is false/true.
Methods Explanation NN IE ECMA
toString() Returns a string Boolean value. (true or false) 3.0
3.0 1.0
valueOf() 4.0 J3 1.0
Examples
1. Variables are used to store data
Coding
<html>
<body>
<script language="JavaScript">
var name = "Hege"
document.write(name)
document.write("<br>")
document.write("<h1>"+name+"</h1>")
</script>
</body>
</html>
Output
Hege
Hege |