Richard's JavaScript Tutorials

Updated 07/18/14

Home
Animation
precachedImages
digitalClock
Object Tag (Audio)
Cookies.htm
Math_Object
Using CSS
The Style Object
Client_Info
customObject
functions
UsingArrays
comments
concatenation
documentwrite
ifelse
Loops
forms
Strings
variables

 

The if...else branch


The if...else branch is used to test if an expression is true or false. There is code written after the if and the else parts of the statement. If the if part of the statement is true then the code written after the if part of the statement is executed. Otherwise the code after the else part of the statement is executed. I will show you an example of this below:

<h1>Washington Redskins Rock!</h1>
<script type="text/javascript">
<!-- Hide from other browsers
var animated_images= confirm("Redskin fans click ok Bucs fans press cancel to exit.");
if (animated_images)
{document.write('<IMG SRC="http://www.cayemay.com/pimp_927.jpeg">');}
else {document.write('
<IMG SRC="http://www.cayemay.com/bucsuck.gif">
');}
// Stop hiding from browsers -->
</script>

This example uses the if...else branch with the help of a confirmation alert box. After this script loads a confirmation box appear on the screen (In some browsers the Javascript will have to be allowed to be shown due to the pop up blocker) with the text "Redskin fans click Ok bucs fans choose cancel to exit ( with an ok button or a cancel button displayed). If you choose the ok button the if part of the statement is true and the code under the if part of the statement executes. In this example a picture (redskin player) is displayed using the document.write() method. If a user is a Bucs fan then choosing the cancel button will make the if part of the statement false thus executing the code under the else part of the statement (document.write method that displays a Bucs suck animated .gif.

Click here to execute my football fan quiz to see how the if...else branch works

Now try substituting my code and add your own text to try creating your own javascript code using the if...else branch.

 

 

This site was last updated 07/08/14