JavaScripting for Interactive Educational Webs

[Intro] [Overview] [Basics] [More] [Forms] [If] [Queries] [Time] [Random] [Loops] [Misc.] [References] [HTML]


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


Exercise: A self-scoring quiz.


[Intro] [Overview] [Basics] [More] [Forms] [If] [Queries] [Time] [Random] [Loops] [Misc.] [References] [HTML]

This page written by Samuel A. Rebelsky.

This page generated on 43 by SamR's Site Suite.