Java Reference
In-Depth Information
In this chapter you look at how decision making is implemented in JavaScript and how you can use
it to make your code smarter.
deCision making—the if and sWitCh statements
All programming languages enable you to make decisions—that is, they enable the program to
follow a certain course of action depending on whether a particular condition is met. This is what
gives programming languages their intelligence.
Conditions are comparisons between variables and data, such as the following:
Is A bigger than B ?
Is X equal to Y ?
Is M not equal to N ?
For example, if the variable today held the day of the week on which you are reading this chapter,
the condition would be this:
Is today equal to Friday?
You'll notice that all of these questions have a yes or no answer—that is, they are boolean‐based and
can only evaluate to true or false . How do you use this to create decision‐making capabilities in
your code? You get the browser to test for whether the condition is true . If (and only if) it is true ,
you execute a particular section of code.
Look at another example. Recall from Chapter 1 the natural English instructions used to
demonstrate how code flows. One of these instructions for making a cup of coffee is:
Has the kettle boiled? If so, then pour water into cup; otherwise, continue to wait.
This is an example of making a decision. The condition in this instruction is “Has the kettle
boiled?” It has a true or false answer. If the answer is true , you pour the water into the cup. If it
isn't true , you continue to wait.
In JavaScript, you can change the flow of the code's execution depending on whether a condition
is true or false , using an if statement or a switch statement. You look at these shortly, but
first we need to introduce some new operators that are essential for the definition of conditions—
comparison operators .
Comparison operators
In Chapter 2 you saw how mathematical functions, such as addition and division, were represented
by symbols, such as plus ( + ) and forward slash ( / ), called operators. You also saw that if you want to
give a variable a value, you can assign to it a value or the result of a calculation using the equals sign
( = ), termed the assignment operator.
Decision making also has its own operators, which enable you to test conditions. Comparison
operators, just like the mathematical operators you saw in the preceding chapter, have a left‐hand
 
Search WWH ::




Custom Search