6.4 else if
We've seen that the
if/else statement is useful for testing a
condition and executing one of two pieces of code, depending on the
outcome. But what about when we need to execute one of many pieces of
code? One way to do this is with an else
if statement. else
if is not really a JavaScript statement, but
simply a frequently used programming idiom that results when repeated
if/else statements are used:
if (n == 1) {
// Execute code block #1
}
else if (n == 2) {
// Execute code block #2
}
else if (n == 3) {
// Execute code block #3
}
else {
// If all else fails, execute block #4
} There is nothing special about this code. It is just a series of
if statements, where each if is
part of the else clause of the previous statement.
Using the else if idiom is
preferable to, and more legible than, writing these statements out in
their syntactically equivalent fully nested form:
if (n == 1) {
// Execute code block #1
}
else {
if (n == 2) {
// Execute code block #2
}
else {
if (n == 3) {
// Execute code block #3
}
else {
// If all else fails, execute block #4
}
}
}
•
Table of Contents
•
Index
•
Reviews
•
Examples
•
Reader Reviews
•
Errata
JavaScript: The Definitive Guide, 4th Edition
By
David Flanagan
Publisher
: O'Reilly
Pub Date
: November 2001
ISBN
: 0-596-00048-0
Pages
: 936
Slots
: 1
This fourth edition of the definitive reference to
JavaScript, a scripting language that can be embedded
directly in web pages, covers the latest version of the
language, JavaScript 1.5, as supported by Netscape 6 and
Internet Explorer 6. The book also provides complete
coverage of the W3C DOM standard (Level 1 and Level 2),
while retaining material on the legacy Level 0 DOM for
backward compatibility.