HTMLisEasy.com
HTML tutorials for the rest of us...
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 >>
Javascript Tutor
Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Javascript Authoring Guide      JavaScript FAQ
HTML 4.0 Reference      Google Groups (Advanced Search)