Javascript Tutor - Lesson 2

Variables.

What's a variable? Let's suppose x=5.

x is a variable. The statement x=5 declares that the value of x is now 5. Can x be something else? Sure, x=6. Now x equals 6. (Hence the name "variable"... it's value can vary.)

Can a variable be something other than a number? Sure. How about x="Joe". Now x equals the string "Joe". (A string by the way is a string of characters... and strings are always enclosed in quotes.)

Can the name of a variable be something other than a letter like x? Sure, myname="Joe". Simple.

How can we incorporate this new found knowledge into our function? Easy...

 
<html>
<head>
<title></title>
 
<script type="text/javascript">
 
function HelloWorld()
{
   myname = "Joe";
   alert(myname);
}
 
</script>
 
</head>
<body>
 
<a href="javascript:HelloWorld()">Hello</a>
 
</body>
</html>

Try it.

(Note again that strings are always enclosed in quotes, but variables are not.)

What we have called is the alert method. Think of a method as a command. Javascript has many methods.

We could make it say Hello + variable...

 
<html>
<head>
<title></title>
 
<script type="text/javascript">
 
function HelloWorld()
{
   myname = "Joe";
   alert("Hello " + myname);
}
 
</script>
 
</head>
<body>
 
<a href="javascript:HelloWorld()">Hello</a>
 
</body>
</html>

Try it.

<< BACK NEXT >>