Javascript Tutor - Lesson 8

If-then statements.

If condition, do something.

 
if (condition)
{
   do something;
}
 
if ( x > 4 )
{
   alert("Hey kids, x is greater than 4!");
}

Have a look at this...

 
<html>
<head>
<title></title>
 
<script type="text/javascript">
 
function Hello()
{
   x = 6;
 
   if ( x > 4)
   {
      alert("Hey kids, x is greater than 4!");
   }
}
 
</script>
 
</head>
<body>
 
<a href="javascript:Hello()">Click here</a>
 
</body>
</html>

Try it.

Understand what's going on? Good. I thought so. An if-then statement is pretty simple to grasp. It is also one of the most powerful tools in your bag of tricks. This simple statement (and its variations) are the brains behind your programs. This is the computer making a decision.

Exercise: Add a prompt box to the above page. When you click on a link, it asks the user for a number. If that number is greater than 4, you get an alert box saying something like "Hey kids, 8 is greater than 4!".

Here is a solution.

Adding to the if (then) statement is the if-else statement...

If condition, do something...
Else, do something else.

 
if (condition)
{
   do something;
}
else
{
   do something else;
}
 
if ( x > 4 )
{
   alert("Hey kids, x is greater than 4!");
}
else
{
   alert("Hey kids, x is NOT greater than 4!");
}

Our example again. This time we'll make x = 3.

 
<html>
<head>
<title></title>
 
<script type="text/javascript">
 
function Hello()
{
   x = 3;
 
   if ( x > 4)
   {
      alert("Hey kids, x is greater than 4!");
   }
   else
   {
      alert("Hey kids, x is NOT greater than 4!");
   }
}
 
</script>
 
</head>
<body>
 
<a href="javascript:Hello()">Click here</a>
 
</body>
</html>

Try it.

Exercise: You guessed it. Add that feature to your last exercise.

Here is a solution.

<< BACK NEXT >>