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
Exercise: A self-scoring quiz.
This page written by Samuel A. Rebelsky.
This page generated on 43 by SamR's Site Suite.