﻿ Appendix A: Exercise Solutions JavaScript Validator     JavaScript Editor ﻿

# Appendix A: Exercise Solutions

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.

## Chapter 2

In this chapter we looked at how JavaScript stores and manipulates data, such as numbers and text.

### Question 1

 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: ```           ``` Save this as ch02_q1.htm. 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.

### Question 2

 The following code uses the prompt() function to get two numbers from the user. It then adds those two numbers together and writes the result to the page. ``` ``` However, if you try the code out, you'll spot that it doesn't work. Why not? Change the code so that it does work. A: The data that the prompt() actually obtains is a string. So both firstNumber and secondNumber contain text that happens to be number characters. When we use the + symbol to add the two variables together, JavaScript assumes that since it's string data, we must want to concatenate the two together and not sum them.To make it explicit to JavaScript that we want to add the numbers together, we need to convert the data to numbers using the parseFloat() function. ``` ``` Save this as ch02_q2.htm. Now the data returned by the prompt() function is converted to a floating-point number before being stored in the firstNumber and secondNumber variables. Then, when we do the addition that is stored in theTotal, JavaScript makes the correct assumption that, because both the variables are numbers, we must mean to add them up and not concatenate them. The general rule is that where we have expressions with only numerical data, the + operator means "do addition." If there is any string data, the + will mean concatenate. JavaScript Validator     JavaScript Editor