An Abbreviated Introduction to JavaScript


Conditionals in JavaScript

Abstract: A short introduction to conditional control structures in JavaScript. Basically, how to tell JavaScript how to make choices.


Introduction

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, ...).

Syntax of Conditionals

As in most languages, JavaScript uses if to name the primary conditional. The syntax for if is relatively terse:

That is,

if (test) {
  code to execute if the test succeeds
}
else {
  code to execute if the test fails
}

Boolean Expressions

What do our tests look like? Sometimes, they are some form of comparison. JavaScript supports six comparison operators

JavaScript also includes three basic Boolean operators

Some examples

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.


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.