In this appendix you'll find some suggested solutions to the exercise questions that were posed at the end of most of the chapters throughout the book.
In this chapter we looked at how JavaScript stores and manipulates data, such as numbers and text.
Write a JavaScript program to convert degrees centigrade into degrees Fahrenheit, and write the result to the page in a descriptive sentence. The JavaScript equation for Fahrenheit to centigrade is degFahren = 9 / 5 * degCent + 32 |
||
A: |
<html> <body> <script language=JavaScript> var degCent = prompt("Enter the degrees in centigrade",0); var degFahren = 9 / 5 * degCent + 32; document.write(degCent + " degrees centigrade is " + degFahren + " degrees Fahrenheit"); </script> </body> </html> We get the degrees centigrade the user wants to convert by using the prompt() function, and store it inside the degCent variable. We then do our calculation, which uses the data stored in degCent and converts it to Fahrenheit. The result is assigned to the degFahren variable. Finally, we write the results to the web page, building it up in a sentence using the concatenation operator +. Note how JavaScript knows in the calculation that degCent is to be treated as a number, but in the document.write() it knows that it should be treated as text for concatenation. So how does it know? Simple, it looks at the context. In the calculation, degCent is surrounded by numbers and numerical only operators, such as * and /. In the document.write(), degCent is surrounded by strings, hence JavaScript assumes the + means concatenate. |