switch (place) {
case 1: place += "st"; break;
case 2: place += "nd"; break;
case 3: place += "rd"; break;
default: place += "th";
}
document.write("You have won " + place + " place!");
In this version, the switch statement terminates correctly as soon as the suffix “nd”
has bee n ap pended. Of c ourse, break doesn’t change the flow of the statements
outside of swit ch. When the switch statement in our example terminate s—either
regularly or through a premature exit caused by one o f the break statements—the
document.write() is always executed after it.
Mike: Don’t we need braces to make a compound statement after case keywords?
Professor: No, we don’t. You can place as many statements following each c ase
keyword as you like. They will all be executed until either switch ends or break is
encountered.
Maria: I think our progr am still doesn’t work p roperly. What about values above 2 0?
The program will produce “21th” instead of the correct “21st,” and “22th” instead of
“22nd ,” and so on.
Professor: You’re right a gain. This pattern actually repeats every 10 numbers, except
for 11, 12, 13, 11 1, 112, 113, and so on. T here are of course more solutions and this
is one of them:
switch (place % 100 <= 20 ? place % 20 : place % 10) {
case 1: ...
8.3 Math Object
Professor: I think it’s about time we started moving to a higher level of programmin g.
You learned quite a bit about primitive data types and how to manipulate them using
operators and some basic co ntrol statements. However, as your programs become
more com plex, you will soon need to organize data a nd code more efficiently in order
for y our projects to stay under control. The concept of objects offers you one aspect
of such data and code organization. Essentially, objects group d ata and code that
logically fit together and hide unnecessary implemen ta tion details from other pa rts of
a program. In object-oriented terminology, data and code that are integrated in an
object are called properties and methods, respectively. Properties define the state of
an object, while methods define its behavior.
You can think of an object in the same way as you think of a real-world object. For
example, your mobile is quite a complex device, yet yo u don’t have to be a rocket
scientist to be able to use it because its actu al implementation is hidden from you.
There’s quite some data stored inside your mobile. Apart from the most obvious
contacts, th ere is a lso information like whether Bluetooth
r
is on or off, or whether
152 Meeting 8. Introducing Objects