O'Reilly logo

Beginning JavaScript, 5th Edition by Jeremy McPeak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

AAnswers to Exercises

This appendix provides the answers to the questions you find at the end of each chapter in this book.

CHAPTER 2

Exercise 1 Question

Write a JavaScript program to convert degrees centigrade into degrees Fahrenheit, and to write the result to the page in a descriptive sentence. The JavaScript equation for Fahrenheit to centigrade is as follows:

degFahren = 9 / 5 * degCent + 32

Exercise 1 Solution

<!DOCTYPE html>

<html lang="en">
<head>
    <title>Chapter 2: Question 1</title>
</head>
<body>
    <script>
        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>

Save this as ch2_question1.html.

Exercise 2 Question

The following code uses the prompt() function to get two numbers from the user. It then adds those two numbers and writes the result to the page:

<!DOCTYPE html>

<html lang="en">
<head>
    <title>Chapter 2, Question 2</title>
</head>
<body>

<script>
    var firstNumber = prompt("Enter the first number","");
    var secondNumber = prompt("Enter the second number","");
    var theTotal = firstNumber + secondNumber;

    document.write(firstNumber + " added to " + secondNumber +
        " equals " + theTotal);
</script>
</body>
</html>

However, if you try out the code, you’ll discover that it doesn’t work. Why not? Change the code so that it does work.

Exercise 2 Solution

The data that the prompt() actually obtains is a string. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required