Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

The if Statement

One of the most important features of a computer language is the capability to test and compare values. This allows your scripts to behave differently based on the values of variables, or based on input from the user.

The if statement is the main conditional statement in JavaScript. This statement means much the same in JavaScript as it does in Englishfor example, here is a typical conditional statement in English:

If the phone rings, answer it.

This statement consists of two parts: a condition (If the phone rings) and an action (answer it). The if statement in JavaScript works much the same way. Here is an example of a basic if statement:

if (a == 1) window.alert("Found a 1!");

This statement includes a condition (if a equals 1) and an action (display a message). This statement checks the variable a and, if it has a value of 1, displays an alert message. Otherwise, it does nothing.

If you use an if statement like the preceding example, you can use a single statement as the action. You can also use multiple statements for the action by enclosing them in braces ({}), as shown here:

if (a == 1) {
   window.alert("Found a 1!");
   a = 0;
}

This block of statements checks the variable a once again. If it finds a value of 1, it displays a message and sets a back to 0.

Conditional Operators

The action part of an if statement can include any of the JavaScript statements you've already learned (and any others, for that matter), but the condition part of the statement uses its own syntax. This is called a conditional expression.

A conditional expression usually includes two values to be compared (in the preceding example, the values were a and 1). These values can be variables, constants, or even expressions in themselves.

By the Way

Either side of the conditional expression can be a variable, a constant, or an expression. You can compare a variable and a value, or compare two variables. (You can compare two constants, but there's usually no reason to.)


Between the two values to be compared is a conditional operator. This operator tells JavaScript how to compare the two values. For instance, the == operator is used to test whether the two values are equal. A variety of conditional operators is available:

  • == Is equal to

  • != Is not equal to

  • < Is less than

  • > Is greater than

  • >= Is greater than or equal to

  • <= Is less than or equal to

By the Way

Be sure not to confuse the equality operator (==) with the assignment operator (=), even though they both might be read as "equals." Remember to use = when assigning a value to a variable, and == when comparing values. Confusing these two is one of the most common mistakes in JavaScript programming.


Combining Conditions with Logical Operators

Often, you'll want to check a variable for more than one possible value, or check more than one variable at once. JavaScript includes logical operators, also known as Boolean operators, for this purpose. For example, the following two statements check different conditions and use the same action:

if (phone == "") window.alert("error!");
if (email == "") window.alert("error!");

Using a logical operator, you can combine them into a single statement:

if (phone == "" || email == "") window.alert("Something's Missing!");

This statement uses the logical Or operator (||) to combine the conditions. Translated to English, this would be, "If the phone number is blank or the email address is blank, display an error message."

An additional logical operator is the And operator, &&. Consider this statement:

if (phone == "" && email == "") window.alert("Both are Missing!");

This statement uses && (And) instead of || (Or), so the error message will only be displayed if both the email address and phone number variables are blank. (In this particular case, Or is a better choice.)

Did you Know?

If the JavaScript interpreter discovers the answer to a conditional expression before reaching the end, it does not evaluate the rest of the condition. For example, if the first of two conditions separated by the && operator is false, the second is not evaluated. You can take advantage of this to improve the speed of your scripts.


The third logical operator is the exclamation mark (!), which means Not. It can be used to invert an expressionin other words, a true expression would become false, and a false one would become true. For example, here's a statement that uses the Not operator:

if (!($phone == "")) alert("phone is OK");

In this statement, the ! (Not) operator inverts the condition, so the action of the if statement is executed only if the phone number variable is not blank. The extra parentheses are necessary because all JavaScript conditions must be in parentheses. You could also use the != (Not equal) operator to simplify this statement:

if ($phone != "") alert("phone is OK");

As with the previous statement, this alerts you if the phone number field is not blank.

Did you Know?

The logical operators are powerful, but it's easy to accidentally create an impossible condition with them. For example, the condition (a < 10 && a > 20) might look correct at first glance. However, if you read it out loud, you get "If a is less than 10 and a is greater than 20"an impossibility in our universe. In this case, Or (||) should have been used.


The else Keyword

An additional feature of the if statement is the else keyword. Much like its English equivalent, else tells the JavaScript interpreter what to do if the condition isn't true. The following is a simple example of the else keyword in action:

if (a == 1) {
   alert("Found a 1!");
   a = 0;
}
else {
   alert("Incorrect value: " + a);
}

This is a modified version of the previous example. This displays a message and resets the variable a if the condition is met. If the condition is not met (if a is not 1), a different message is displayed.

By the Way

Like the if statement, else can be followed either by a single action statement or by a number of statements enclosed in braces.


Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Hour 5. Using Variables, Strings, and Arrays
Hour 6. Using Functions and Objects
Hour 7. Controlling Flow with Conditions and Loops
The if Statement
Using Shorthand Conditional Expressions
Testing Multiple Conditions with if and else
Using Multiple Conditions with switch
Using for Loops
Using while Loops
Using do…while Loops
Working with Loops
Looping Through Object Properties
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 8. Using Built-in Functions and Libraries
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele