Java Reference
In-Depth Information
Decisions and Loops
What You Will learn in this Chapter:
➤
Comparing number and string values
➤
Making decisions with the if, else, and switch statements
➤
Repeating code for as long as a condition is true
Wrox.Com Code doWnloads for this Chapter
You can find the wrox.com code downloads for this chapter at
http://www.wiley.com/go/
BeginningJavaScript5E
o
n the Download Code tab. You can also view all of the examples
So far, you've seen how to use JavaScript to get user input, perform calculations and tasks with
that input, and write the results to a web page. However, a pocket calculator can do all this, so
what is it that makes computers different? That is to say, what gives computers the appearance
of having intelligence? The answer is the capability to make decisions based on information
gathered.
How will decision‐making help you in creating websites? In the preceding chapter you wrote
some code that converted temperature in degrees Fahrenheit to centigrade. You obtained the
degrees Fahrenheit from the user using the
prompt()
function. This worked fine if the user
entered a valid number, such as
50
. If, however, the user entered something invalid for the
Fahrenheit temperature, such as the string
aaa
, you would find that your code no longer works
as expected. Now, if you had some decision‐making capabilities in your program, you could
check to see if what the user has entered is valid. If it is, you can do the calculation, and if it
isn't, you can tell the user why and ask him to enter a valid number.
Validation of user input is probably one of the most common uses of decision making in
JavaScript, but it's far from being the only use.