Java Reference
In-Depth Information
The curly braces,
{}
, have a special purpose in JavaScript: They mark out a
block
of code. Marking
out lines of code as belonging to a single block means that JavaScript will treat them all as one
piece of code. If the condition of an
if
statement is
true
, JavaScript executes the next line or
block of code following the
if
statement. In the preceding example, the block of code has only one
statement, so we could equally as well have written this:
if (roomTemperature > 80)
roomTemperature = roomTemperature - 10;
However, if you have a number of lines of code that you want to execute, you need the braces to
mark them out as a single block of code. For example, a modified version of the example with three
statements of code would have to include the braces:
if (roomTemperature > 80) {
roomTemperature = roomTemperature - 10;
alert("It's getting hot in here");
alert("Air conditioning switched on");
}
A particularly easy mistake to make is to forget the braces when marking out a block of code to
be executed. Instead of the code in the block being executed when the condition is true, you'll find
that
only the first line
after the
if
statement is executed. However, the other lines will always be
executed regardless of the outcome of the test condition. To avoid mistakes like these, it's a good
idea to always use braces, even where there is only one statement. If you get into this habit, you'll be
less likely to leave them out when they are actually needed.
the if Statement
trY it out
Let's return to the temperature converter example from Chapter 2 and add some decisionāmaking
functionality.
1.
Enter the following code and save it as
ch3_example1.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 3, Example 1</title>
</head>
<body>
<script>
var degFahren = parseInt(prompt("Enter the degrees Fahrenheit", 32), 10);
var degCent = 5/9 * (degFahren - 32);
document.write(degFahren + "\xB0 Fahrenheit is " + degCent +
"\xB0 centigrade<br />");
if (degCent < 0) {
document.write("That's below the freezing point of water");
}
if (degCent == 100)