[Overview] [Basics] [More] [Fun] [Class 2] [If] [Functions] [Timing] [Queries] [References] [Examples] [Libraries] [Assignments]
Abstract: A short introduction to conditional control structures in JavaScript. Basically, how to tell JavaScript how to make choices.
So far, the JavaScript programs we've been writing are relatively straightforward. Each statement in a sequence is executed in order. (Sometimes our sequences seem to have only one step.) However, one of the great powers of programming languages, and one of the reasons we need JavaScript for our pages is the conditional.
Conditional structures permit programs to test a condition and execute different code depending on the value of that condition. Usually, these are true/false conditions (are two values the same, does a string appear in another string, ...).
As in most languages, JavaScript uses if to name
the primary conditional. The syntax for if is
relatively terse:
if
else and more code to execute
That is,
if (test) {
code to execute if the test succeeds
}
else {
code to execute if the test fails
}
What do our tests look like? Sometimes, they are some form of comparison. JavaScript supports six comparison operators
== test for equality
!= test for inequaltiy
> test greater than
>= test greater than or equal
< test less than
<= test less than or equal
JavaScript also includes three basic Boolean operators
&& "ands" two expressions
|| "ors" two expressions
! negates an expression
Suppose I want to print different pages, depending on what someone has entered as a user name. I might write,
<script language="javascript">
name = prompt("What is your name?", "");
if (name == "SamR") {
document.write("<P>You are the strangest professor I've ever met.</P>");
}
else {
document.write("<P>Welcome, " + name + ".;/P>");
}
</script>
You may want to visit a similar example.
One might also use this technique to provide a form of ``password protection''
<script language="javascript">
password = prompt("Please enter the password: ","")
if (password != "AMMI") {
location = "../index.html";
}
</script>
You may want to visit a similar example.
[Overview] [Basics] [More] [Fun] [Class 2] [If] [Functions] [Timing] [Queries] [References] [Examples] [Libraries] [Assignments]
Source text written by Samuel A. Rebelsky.
This page may be found at http://www.math.grin.edu/~rebelsky/Tutorials/JavaScript/Spring1999/cond.html
Source text last modified Wed Apr 14 12:18:37 1999.
This page generated on Wed Apr 14 12:24:52 1999 by SiteWeaver. Validate this page's HTML.