Source Code from Programming Fundamentals in JavaScript

This article contains the source code for all complete programming examples from the book Programming Fundamentals in JavaScript. You can download this zip file that contains all the source code files or you can download individual files below.

Chapter 3. HTML Basics

Example 3.1 – Horse Rentals Copy example 3.1 to the clipboardOpen example 3.1 in your browserDownload example 3.1 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<!-- The following meta tag tells your browser
that this document uses the 8-bit Unicode
Transformation Format encoding. -->
<meta charset="utf-8">
<title>Horse Rentals</title>
</head>

<body>
<h1>Horse Rentals</h1>
<p>We rent horsies, big horsies, medium sized
horsies, and little horsies (big dogs really). Of
course, this costs a great deal of money, and in
order for us to allow you to take the horsies
anywhere, you must sign a lot of paper work, about
the same amount as if you were buying a house or
being admitted to a hospital (which might happen
if you fall off one of our horsies).</p>

<p>We rent horsy saddles and other leather and
metal stuff. Just ask for what you want, and we
probably have it. These are used mostly to control
the horsies, which they don't like. If you don't
take great care when putting these on the horsies,
you might be admitted to the hospital as mentioned
in the above paragraph.</p>

<p>We also rent horsy trailers. These trailers
require a truck the size of Texas that drinks diesel
in order to actually pull them. Of course, if you
don't have a truck that fits this description, we'll
rent you one. See the first paragraph again for our
rental terms (big money).</p>
</body>
</html>

Example 3.2 – First HTML Form Copy example 3.2 to the clipboardOpen example 3.2 in your browserDownload example 3.2 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<!-- The following meta tag tells your browser
that this document uses the 8-bit Unicode
Transformation Format encoding. -->
<meta charset="utf-8">
<title>Send a Text Message</title>
</head>

<body>
<h1>Send a Text Message</h1>
<p>
From (your 10-digit wireless phone number):
<input type="text" id="txtFrom" size="10">
</p>

<p>
To (10-digit wireless phone number):
<input type="text" id="txtTo" size="10">
</p>

<p>
Message:<br>
<textarea id="txaMessage" rows="8" cols="40">
</textarea>
</p>

<p>
<button type="button" onclick="sendText()">Send</button>
<button type="button" onclick="clearForm()">Clear</button>
</p>
</body>
</html>

Chapter 4. JavaScript Basics

Example 4.1 – First JavaScript Program Copy example 4.1 to the clipboardOpen example 4.1 in your browserDownload example 4.1 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <title>My First JavaScript Program</title>

    <script>
        "use strict";

        /* Defining Table
         * Input: No user input
         * Processing: None
         * Output: The message "Water is delicious!"
         */
        function showMessage() {
            // The next line of code causes the computer
            // to open a popup window that contains the
            // words "Water is delicious!"
            alert("Water is delicious!");
        }
    </script>
</head>

<body>
<button type="button" onclick="showMessage()">Message</button>
</body>
</html>

Example 4.2 – Greeting Copy example 4.2 to the clipboardOpen example 4.2 in your browserDownload example 4.2 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>A Program to Say Hello</title>
<script>
/* Defining Table
 * Input: A person's name
 * Processing: Create a greeting for that person
 * Output: The greeting
 */
function greetUser() {
    // This line prompts the user to type in his name.
    let name = prompt("Please enter your name");

    // Create a personalized greeting for the user.
    let greeting = "Hello " + name +
            ".  I hope you are well today.";

    // The next line causes the computer to display
    // a greeting to the user in a popup window.
    alert(greeting);
}
</script>
</head>

<body>
<button type="button" onclick="greetUser()">Hello</button>
</body>
</html>

Example 4.3 – Personalized Scripture Copy example 4.3 to the clipboardOpen example 4.3 in your browserDownload example 4.3 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Personalized Scripture</title>
<script>
/* Defining Table
 * Input: A person's name
 * Processing: Create a verse of scripture for that person
 * Output: The scripture
 */
function applyScripture() {
    // Get the user's name from the text field that has the id
    // of "nameInputBox" and store it in a variable named name.
    let name = document.getElementById('nameInputBox').value;

    // Use string concatenation to create a verse
    // of scripture personalized for the user.
    let scripture = "I, " + name + ", having been born of" +
        " goodly parents, therefore I was taught somewhat" +
        " in all the learning of my father.";

    // Display the scripture in the
    // div that has the id "outputDiv".
    document.getElementById('outputDiv').innerHTML = scripture;
}
</script>
</head>

<body>
Please enter your name: <input type="text" id="nameInputBox">
<button type="button" onclick="applyScripture()">Verse</button>
<div id="outputDiv"></div>
</body>
</html>

Chapter 5. Variables and Arithmetic

Example 5.8 – Celsius to Fahrenheit Copy example 5.8 to the clipboardOpen example 5.8 in your browserDownload example 5.8 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Convert Celsius to Fahrenheit</title>

<script>
/* Input: a temperature in Celsius
 * Processing: convert the temperature from Celsius to Fahrenheit
 * Output: the temperature converted to Fahrenheit
 */
function celsToFahr() {
    // Read a Celsius temperature from the user.
    let text = document.getElementById('celsiusInputBox').value;

    // Convert what the user typed from text into a number.
    let c = parseFloat(text);

    // Convert the Celsius temperature into Fahrenheit.
    let f = c * 9 / 5 + 32;

    // Display the Fahrenheit temperature to the user.
    document.getElementById('fahrenDiv').innerHTML = f;
}
</script>
</head>

<body>
Enter a temperature in Celsius:
    <input type="text" id="celsiusInputBox">
<button type="button" onclick="celsToFahr()">Convert</button>
<div id="fahrenDiv"></div>
</body>
</html>

Example 5.9 – Fahrenheit to Celsius Copy example 5.9 to the clipboardOpen example 5.9 in your browserDownload example 5.9 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Convert Fahrenheit to Celsius</title>

<script>
/* Input: a temperature in Fahrenheit
 * Processing: convert the temperature from Fahrenheit to Celsius
 * Output: the temperature converted to Celsius
 */
function fahrToCels() {
    // Read a Fahrenheit temperature from the user.
    let text = document.getElementById('fahrenInputBox').value;

    // Convert what the user typed from text into a number.
    let f = parseFloat(text);

    // Convert the Fahrenheit temperature into Celsius.
    let c = 5 / 9 * (f - 32);

    // Display the Celsius temperature to the user.
    document.getElementById('celsiusDiv').innerHTML = c;
}
</script>
</head>

<body>
Enter a temperature in Fahrenheit:
    <input type="text" id="fahrenInputBox">
<button type="button" onclick="fahrToCels()">Convert</button>
<div id="celsiusDiv"></div>
</body>
</html>

Example 5.22 – Volume of a Cylinder Copy example 5.22 to the clipboardOpen example 5.22 in your browserDownload example 5.22 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Volume</title>

<script>
/* Input: radius and height of a cylinder
 * Processing: Calculate the volume of the cylinder.
 * Output: the volume
 */
function volume() {
    // Get the radius and height from the user.
    let r = parseFloat(
            document.getElementById('radiusInput').value);
    let h = parseFloat(
            document.getElementById('heightInput').value);

    // Compute the volume of the cylinder.
    let v = Math.PI * r * r * h;

    // Display the volume to the user.
    document.getElementById('outputDiv').innerHTML = v;
}
</script>
</head>

<body>
Radius <input type="text" id="radiusInput" size="5"><br>
Height <input type="text" id="heightInput" size="5"><br>
<button type="button" onclick="volume()">Volume</button>
<div id="outputDiv"></div>
</body>
</html>

Example 5.23 – Distance between Two Points Copy example 5.23 to the clipboardOpen example 5.23 in your browserDownload example 5.23 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Distance</title>

<script>
/* Input: x and y for two points: x1, y1, x2, y2
 * Processing:
 *   1. Calculate the distance between the two points.
 *   2. Round the distance to two digits after the decimal.
 * Output: the rounded distance
 */
function distance() {
    // Get the coordinates for two points from the user.
    let x1 = parseFloat(
            document.getElementById('x1inputBox').value);
    let y1 = parseFloat(
            document.getElementById('y1inputBox').value);
    let x2 = parseFloat(
            document.getElementById('x2inputBox').value);
    let y2 = parseFloat(
            document.getElementById('y2inputBox').value);

    // Compute the distance between the two points.
    let dx = x2 - x1;
    let dy = y2 - y1;
    let dist = Math.sqrt(dx * dx + dy * dy);

    // Round the distance to two digits after the decimal.
    let digits = 2;
    let multiplier = Math.pow(10, digits);
    dist = Math.round(dist * multiplier) / multiplier;

    // Display the distance to the user.
    document.getElementById('outputDiv').innerHTML = dist;
}
</script>
</head>

<body>
Please enter the x and y coordinates for two points:<br>
(x1, y1) <input type="text" id="x1inputBox" size="3">
         <input type="text" id="y1inputBox" size="3"><br>
(x2, y2) <input type="text" id="x2inputBox" size="3">
         <input type="text" id="y2inputBox" size="3"><br>
<button type="button" onclick="distance()">Distance</button>
<div id="outputDiv"></div>
</body>
</html>

Chapter 6. Selection

Example 6.1 – Is an Integer Even? Copy example 6.1 to the clipboardOpen example 6.1 in your browserDownload example 6.1 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Is Even?</title>

<script>
/* Input: An integer
 * Processing: Determine if the integer is even or odd
 * Output: A message that says the integer is even or odd
 */
function isEven() {
    // Get the user input from a text
    // field and convert it to an integer.
    let text = document.getElementById('inputBox').value;
    let number = parseInt(text);

    // Choose a message.
    let message;
    if ((number % 2) == 0) {
        message = number + " is an even integer";
    }
    else {
        message = number + " is an odd integer";
    }

    // Display the message to the user.
    document.getElementById('output').innerHTML = message;
}
</script>
</head>

<body>
Please enter an integer: <input type="text" id="inputBox">
<button type="button" onclick="isEven()">Is Even?</button>
<div id="output"></div>
</body>
</html>

Example 6.4 – Quadratic Formula Copy example 6.4 to the clipboardOpen example 6.4 in your browserDownload example 6.4 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Quadratic Formula</title>

<script>
/* Input: Three coefificients from a quadratic equation.
 * Processing: If they exist, compute
 *     the root or roots of the equation
 * Output:
 *     The root or roots of the equation or
 *    "undefined" if they don't exist.
 */
function quadratic() {
    // Get three coefficients a, b, and c
    // for a quadratic equation from the user.
    let a = parseFloat(document.getElementById('inputA').value);
    let b = parseFloat(document.getElementById('inputB').value);
    let c = parseFloat(document.getElementById('inputC').value);

    // Compute the root or roots of the
    // quadratic equation if they exist.
    let discr = b * b - 4 * a * c;
    let root1, root2;
    if (discr >= 0) {
        let sq = Math.sqrt(discr);
        root1 = (-b + sq) / (2 * a);
        root2 = (-b - sq) / (2 * a);
    }

    // Display the roots to the user.
    document.getElementById('output').innerHTML =
            root1 + ' ' + root2;
}
</script>
</head>

<body>
y = <input type="text" id="inputA" size="3"> x<sup>2</sup> +
    <input type="text" id="inputB" size="3"> x +
    <input type="text" id="inputC" size="3">
<button type="button" onclick="quadratic()">Compute Roots</button>
<div id="output"></div>
</body>
</html>

Example 6.8 – Ticket Price Copy example 6.8 to the clipboardOpen example 6.8 in your browserDownload example 6.8 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Ticket Price</title>
<script>
/* Input: A person's age and the number
 *     of games that person has attended
 * Processing: Determine the price to charge
 *     that person for a ticket to a game
 * Output: The ticket price
 */
function ticketPrice() {
    // Get a person's age and number
    // of games attended from the user.
    let age = parseInt(document.getElementById('ageBox').value);
    let gamesAttended =
            parseInt(document.getElementById('gamesBox').value);

    // Based on the person's age and number of number
    // of games attended, determine a ticket price.
    let price;
    if (age < 18) {
        if (gamesAttended < 6)
            price = 8.0;
        else if (gamesAttended < 11)
            price = 6.0;
        else
            price = 5.0;
    }
    else if (age < 55) {
        if (gamesAttended < 11)
            price = 10.0;
        else
            price = 8.0;
    }
    else {
        if (gamesAttended < 11)
            price = 8.0;
        else
            price = 6.0;
    }

    // Display the ticket price for the user to see.
    document.getElementById('priceDiv').innerHTML = price;
}
</script>
</head>

<body>
Age: <input type="text" id="ageBox" size="3"><br>
Number of games attended:
    <input type="text" id="gamesBox" size="3"><br>
<button type="button" onclick="ticketPrice()">Ticket Price</button>
<div id="priceDiv"></div>
</body>
</html>

Chapter 7. Logic

Example 7.2 – Groups for Girls Copy example 7.2 to the clipboardOpen example 7.2 in your browserDownload example 7.2 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Which Class</title>
<script>
/* Input: A girl's age
 * Processing: If statements to choose a class
 * Output: Name of the class
 */
function chooseClass() {
    let age = parseInt(document.getElementById('age').value);

    let group;
    if (age <= 11) {
        group = 'Primary';
    }
    else if (age == 12 || age == 13) {
        group = 'Beehive';
    }
    else if (age == 14 || age == 15) {
        group = 'Mia Maid';
    }
    else if (age == 16 || age == 17) {
        group = 'Laurel';
    }
    else {
        group = 'Relief Society';
    }

    document.getElementById('output').innerHTML = group;
}
</script>
</head>

<body>
Please enter your age: <input type="text" id="age" size="3"><br>
<button type="button" onclick="chooseClass()">Class</button>
<div id="output"></div>
</body>
</html>

Example 7.3 – Groups for Boys Copy example 7.3 to the clipboardOpen example 7.3 in your browserDownload example 7.3 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Which Group</title>
<script>
/* Input: A boy's age
 * Processing: If statements to choose a group
 * Output: Name of the group
 */
function chooseGroup() {
    let age = parseInt(document.getElementById('age').value);

    let group;
    if (age < 7) {
        group = 'When you are 7 years old,' +
                ' you can become a Tiger Scout.'
    }
    else if (age == 7) {
        group = 'Tiger';
    }
    else if (age == 8) {
        group = 'Wolf';
    }
    else if (age == 9) {
        group = 'Bear';
    }
    else if (age == 10) {
        group = 'Webelos';
    }
    else if (11 <= age && age <= 13) {
        group = 'Boy Scout';
    }
    else if (14 <= age && age <= 20) {
        group = 'Venture';
    }
    else {
        group = 'You are too old to join scouting as a' +
                ' participant. Perhaps you would like' +
                ' to volunteer as a leader.';
    }

    document.getElementById('output').innerHTML = group;
}
</script>
</head>

<body>
Please enter your age: <input type="text" id="age" size="3"><br>
<button type="button" onclick="chooseGroup()">Group</button>
<div id="output"></div>
</body>
</html>

Example 7.4 – Drive on the Autopia Copy example 7.4 to the clipboardOpen example 7.4 in your browserDownload example 7.4 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Are you tall enough to drive on the Autopia?</title>

<script>
/* Input: the height of a driver and an optional passenger
 * Processing: Determine if a driver and
 *     optional passenger may ride the Autopia
 * Output: "Enjoy the ride!" or
 *    "Sorry, to drive a car on the Autopia, you must be at least
 *    54 inches tall or at least 32 inches tall and accompanied
 *    by a passenger who is at least 54 inches tall."
 */
function checkHeight() {
    let driver = parseInt(
            document.getElementById('driverBox').value);
    let passenger = parseInt(
            document.getElementById('passengerBox').value);

    let message;
    if (driver >= 54 || (driver >= 32 && passenger >= 54)) {
        message = 'Enjoy the ride!';
    }
    else {
        message = 'Sorry, to drive a car on the Autopia,' +
            ' you must be at least 54 inches tall or at' +
            ' least 32 inches tall and accompanied by a' +
            ' passenger who is at least 54 inches tall.';
    }

    document.getElementById('outputDiv').innerHTML = message;
}
</script>
</head>

<body>
<h1>Are you tall enough to drive on the Autopia?</h1>
Driver's height in inches:
    <input type="text" id="driverBox" size="3"><br>
Passenger's height in inches:
    <input type="text" id="passengerBox" size="3" value="0"><br>
<button type="button" onclick="checkHeight()">Check Height</button>
<div id="outputDiv"></div>
</body>
</html>

Chapter 8. Repetition

Example 8.10 – Future Value of an Investment Copy example 8.10 to the clipboardOpen example 8.10 in your browserDownload example 8.10 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Compound Interest</title>

<script>
/* Input:
 *    An amount to invest: balance
 *    The annual rate of growth: annualRate
 *    The number of months to invest: numMonths
 * Processing: Use a loop to compute the balance of
 *     an account after a bank has paid interest for
 *     numMonths number of months.
 * Output: The balance after numMonths have passed.
 */
function futureValue() {
    let balance = parseFloat(
            document.getElementById('balance').value);
    let annualRate = parseFloat(
            document.getElementById('annualRate').value);
    let numMonths = parseInt(
            document.getElementById('months').value);
    let monthlyRate = annualRate / 12;

    // For each month, compute the interest
    // and add it to the balance.
    for (let month = 1;  month <= numMonths;  month++) {
        // Compute the interest for a month.
        let interest = balance * monthlyRate;

        // Round the interest to pennies.
        interest = Math.round(interest * 100) / 100;

        // Add the interest to the balance.
        balance += interest;
    }

    // Display the resulting balance for the user to see.
    document.getElementById('output').innerHTML =
        'Your balance after ' + numMonths +
        ' months will be $' + balance;
}
</script>
</head>

<body>
Principal:
    <input type="text" id="balance" size="7"><br>
Annual growth rate:
    <input type="text" id="annualRate" size="5"><br>
Number of months:
    <input type="text" id="months" size="3"><br>
<button type="button"
    onclick="futureValue()">Future Value</button>
<div id="output"></div>
</body>
</html>

Example 8.12 – Is an Integer Prime? (long version) Copy example 8.12 to the clipboardOpen example 8.12 in your browserDownload example 8.12 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Prime Number</title>

<script>
/* Input: an integer
 * Processing: determine if the given integer is prime.
 * Output: __ is prime OR __ is not prime
 */
function isPrime() {
    let candidate = parseInt(
            document.getElementById('integerBox').value);

    // Count the number of factors
    // that evenly divide candidate.
    let factorCount = 0;
    for (let divisor = 1;  divisor <= candidate;  divisor++) {
        let remainder = candidate % divisor;
        if (remainder == 0) {
            factorCount++;
        }
    }

    // Determine the output and show it to the user.
    let output;
    if (factorCount == 2) {
        output = candidate + ' is prime';
    }
    else {
        output = candidate + ' is not prime';
    }
    document.getElementById('outputDiv').innerHTML = output;
}
</script>
</head>

<body>
Please enter an integer:
    <input type="text" id="integerBox"><br>
<button type="button" onclick="isPrime()">Is Prime</button>
<div id="outputDiv"></div>
</body>
</html>

Example 8.13 – Is an Integer Prime? (short version) Copy example 8.13 to the clipboardOpen example 8.13 in your browserDownload example 8.13 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Prime Number</title>

<script>
/* Input: an integer
 * Processing: determine if the given integer is prime.
 * Output: __ is prime OR __ is not prime
 */
function isPrime() {
    let candidate = parseInt(
            document.getElementById('integerBox').value);
    let limit = Math.sqrt(candidate);
    let prime = true;

    // Find the first integer that
    // evenly divides candidate.
    for (let divisor = 2;  divisor <= limit;  divisor++) {
        let remainder = candidate % divisor;
        if (remainder == 0) {
            prime = false;
            break;
        }
    }

    // Determine the output and show it to the user.
    let output;
    if (prime) {
        output = candidate + ' is prime';
    }
    else {
        output = candidate + ' is not prime';
    }
    document.getElementById('outputDiv').innerHTML = output;
}
</script>
</head>

<body>
Please enter an integer:
    <input type="text" id="integerBox"><br>
<button type="button" onclick="isPrime()">Is Prime</button>
<div id="outputDiv"></div>
</body>
</html>

Chapter 9. Functions

Example 9.9 – Is an Integer Even? (long version) Copy example 9.9 to the clipboardOpen example 9.9 in your browserDownload example 9.9 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Is Even</title>

<script>
/* Input: An integer
 * Processing: Determine if the integer is even or not
 * Output: A message stating if the integer is even or not
 */
function doInputOutput() {
    let number = parseInt(
            document.getElementById('numberInputBox').value);
    let result = isEven(number);
    document.getElementById('outputDiv').innerHTML =
        number + ' is even: ' + result;
}


// Returns true if value is an even
// integer; otherwise returns false.
function isEven(value) {
    if ((value % 2) == 0) {
        return true;
    }
    else {
        return false;
    }
}
</script>
</head>

<body>
Please enter an integer: <input type="text" id="numberInputBox">
<button type="button" onclick="doInputOutput()">Is Even?</button>
<div id="outputDiv"></div>
</body>
</html>

Example 9.10 – Is an Integer Even? (short version) Copy example 9.10 to the clipboardOpen example 9.10 in your browserDownload example 9.10 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Is Even</title>

<script>
/* Input: An integer
 * Processing: Determine if the integer is even or not
 * Output: A message stating if the integer is even or not
 */
function doInputOutput() {
    let number = parseInt(
            document.getElementById('numberInputBox').value);
    let result = isEven(number);
    document.getElementById('outputDiv').innerHTML =
        number + ' is even: ' + result;
}


// Returns true if value is an even
// integer; otherwise returns false.
function isEven(value) {
    return (value % 2) == 0;
}
</script>
</head>

<body>
Please enter an integer: <input type="text" id="numberInputBox">
<button type="button" onclick="doInputOutput()">Is Even?</button>
<div id="outputDiv"></div>
</body>
</html>

Example 9.11 – Area of a Triangle Copy example 9.11 to the clipboardOpen example 9.11 in your browserDownload example 9.11 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Triangle Area</title>

<script>
/* Input: No user input
 * Processing: Compute the area of a triangle
 *     with side lengths 4, 2, and 5
 * Output: The area of the triangle
 */
function testTriangle() {
    let r = triangleArea(4, 2, 5);
    document.getElementById('outputDiv').innerHTML = r;
}


// Computes and returns the area of a
// triangle with side lengths a, b, and c.
function triangleArea(a, b, c) {
    let s = (a + b + c) / 2;
    let area = Math.sqrt(s * (s-a) * (s-b) * (s-c));
    return area;
}
</script>
</head>

<body>
<button type="button" onclick="testTriangle()">Test</button>
<div id="outputDiv"></div>
</body>
</html>

Example 9.12 – Surface Area of a Pyramid Copy example 9.12 to the clipboardOpen example 9.12 in your browserDownload example 9.12 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Surface Area of a Pyramid</title>

<script>
/* Input: No user input
 * Processing: Compute the surface area of the
 *     triangular faces of a regular pyramid
 *     that has base 8 and height 7.
 * Output: The surface area of the pyramid
 */
function testPyramid() {
    let pa = pyramidSurfaceArea(8, 7);
    document.getElementById('outputDiv').innerHTML = pa;
}


// Computes and returns the surface area of the
// four triangular faces of a regular pyramid
// with the specified base length and height.
function pyramidSurfaceArea(base, height) {
    let edge = Math.sqrt(base*base/2 + height*height);
    let triArea = triangleArea(base, edge, edge);
    let pyramidArea = 4 * triArea;
    return pyramidArea;
}


// Computes and returns the area of a
// triangle with side lengths a, b, and c.
function triangleArea(a, b, c) {
    let s = (a + b + c) / 2;
    let area = Math.sqrt(s * (s-a) * (s-b) * (s-c));
    return area;
}
</script>
</head>

<body>
<button type="button" onclick="testPyramid()">Test</button>
<div id="outputDiv"></div>
</body>
</html>

Example 9.13 – How Long to Invest Copy example 9.13 to the clipboardOpen example 9.13 in your browserDownload example 9.13 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>How Long to Invest</title>

<script>
/* Input: No user input
 * Processing: Determine the number of months required
 *     to grow an initial investment from $100 to at
 *     least $103 if it grows at an annual rate of 6%.
 * Output: The number of months.
 */
function testInvest() {
    let m = determineMonths(100, 0.06, 103);
    document.getElementById('outputDiv').innerHTML = m;
}


// Computes and returns the number of months
// needed for principal invested at a constant
// annual rate to grow to a target amount.
function determineMonths(principal, annualRate, target) {
    let monthlyRate = annualRate / 12;
    let balance = principal;
    let month = 0;

    // Repeat while the balance of the
    // investment is less than the target.
    while (balance < target) {

        // Compute the the monthly interest and round
        // it to two digits after the decimal point.
        let interest = balance * monthlyRate;
        interest = Math.round(interest * 100) / 100;

        // Add the interest to the investment balance.
        balance += interest;

        month++;
    }

    // Return the number of months
    // necessary to reach the target.
    return month;
}
</script>
</head>

<body>
<button type="button" onclick="testInvest()">Test</button>
<div id="outputDiv"></div>
</body>
</html>

Example 9.14 – Greatest Common Divisor Copy example 9.14 to the clipboardOpen example 9.14 in your browserDownload example 9.14 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Greatest Common Divisor</title>

<script>
/* Input: No user input
 * Processing: Call the gcd function
 * Output: The greatest common divisor of -24 and 472
 */
function testGCD() {
    let x = -24;
    let y = 472;
    let divisor = gcd(x, y);
    document.getElementById('output').innerHTML = divisor;
}


// Finds and returns the greatest common
// divisor of two integers a and b.
function gcd(a, b) {
    // Ensure a and b are not negative.
    a = Math.abs(a);
    b = Math.abs(b);

    // Ensure a is greater than or equal to b.
    if (a < b) {
        let swap = a;
        a = b;
        b = swap;
    }

    // Repeat until the computer finds
    // the greatest common divisor.
    do {
        let r = a % b;
        a = b;
        b = r;
    } while (b != 0);

    // Return the greatest common divisor.
    return a;
}
</script>
</head>

<body>
<button type="button" onclick="testGCD()">Test</button>
<div id="output"></div>
</body>
</html>

Chapter 10. Arrays

Example 10.14 – Parallel Arrays Copy example 10.14 to the clipboardOpen example 10.14 in your browserDownload example 10.14 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Student ID to Name</title>
<script>
// The values in these parallel arrays can be hard coded
// into a program, or even better, they can be read from
// a file or database.
let studentIDs = ['07-153-4276', '34-513-3186', '26-430-0198'];
let studentNames = ['Felix', 'Jonathan', 'Grace'];

/* Input: a student's ID
 * Processing: find the student's name
 * Output: the student's name
 */
function findName() {
    // Get the student's ID.
    let studID = document.getElementById('studID').value;

    // Use linear search to find the student's ID.
    let index = linearSearch(studentIDs, studID);

    let name;
    if (index == -1) {
        // The student ID that the user entered
        // is not stored in the studentIDs array.
        name = 'No such student ID';
    }
    else {
        // Get the student's name.
        name = studentNames[index];
    }

    // Display the student's name for the user to see.
    document.getElementById('output').innerHTML = name;
}


// If key is in list, returns the first index where
// key is located within list; otherwise returns -1.
function linearSearch(list, key) {
    let index = -1;
    for (let i = 0;  i < list.length;  i++) {
        if (list[i] == key) {
            index = i;
            break;
        }
    }
    return index;
}
</script>
</head>

<body>
Student ID: <input type="text" id="studID">
<button type="button" onclick="findName()">Name</button>
<div id="output"></div>
</body>
</html>

Example 10.17 – Find a Range Copy example 10.17 to the clipboardOpen example 10.17 in your browserDownload example 10.17 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Compute Total</title>
<script>
/* Input: The subtotal for a customer's purchases
 * Processing: Compute a discounted amount and sales tax
 *     and add them together to get the total amount that
 *     the customer owes.
 * Output: The total that the customer owes.
 */
function computeTotal() {
    // Get the subtotal from the user.
    let subtotal = parseFloat(
            document.getElementById('subtotal').value);

    // Compute the customer's total.
    let discounted = getDiscountedAmount(subtotal);
    let tax = getSalesTax(discounted);
    let total = discounted + tax;

    // Display the total for the customer to see.
    document.getElementById('total').innerHTML = total;
}


// The values in these parallel arrays can be
// hard coded into your program, or even better,
// they can be read from a file or database.
let limits = [300, 600, 1000];
let rates = [0, 0.02, 0.025, 0.03];

// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
    // Find the purchase range.
    for (let i = 0;  i < limits.length;  i++) {
        if (purchase < limits[i]) {
            break;
        }
    }

    // Get the discount rate that
    // corresponds to the purchase range.
    let rate = rates[i];

    // Compute the discount amount and round it to pennies.
    let discount = purchase * rate;
    discount = roundToPlaces(discount, 2);

    // Compute and return the discounted price.
    return purchase - discount;
}


// Computes and returns the sales tax for a purchase amount.
function getSalesTax(purchase) {
    let taxRate = 0.06;
    let tax = purchase * taxRate;
    tax = roundToPlaces(tax, 2);
    return tax;
}


// Rounds x to digits places after the decimal point.
function roundToPlaces(x, digits) {
    let multiplier = Math.pow(10, digits);
    let rounded = Math.round(x * multiplier) / multiplier;
    return rounded;
}
</script>
</head>

<body>
<h2>Compute Total</h2>
Subtotal <input type="text" id="subtotal" size="5"><br>
<button type="button" onclick="computeTotal()">Total</button>
<div id="total"></div>
</body>
</html>

Example 10.20 – Sort a List of Strings Copy example 10.20 to the clipboardOpen example 10.20 in your browserDownload example 10.20 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Sort Strings</title>

<script>
/* Input: A list of text items, each item on a separate line.
 * Processing:
 *     Split the text items into an array.
 *     Sort the array.
 *     Join the array into a string.
 * Output: The sorted list of text items
 */
function process() {
    // Get the text entered by the user.
    let text = document.getElementById('input').value;

    // Split the text at each new
    // line into an array of strings.
    let list = text.split('\n');

    // Sort the array of strings.
    list.sort();

    // Join the sorted array into a string
    // of text separated by newline characters.
    let output = list.join('\n');

    // Display the string for the user to see.
    document.getElementById('output').value = output;
}
</script>
</head>

<body>
<textarea id="input" rows="16" cols="20"></textarea>
<button type="button" onclick="process()">Sort</button>
<textarea id="output" rows="16" cols="20"></textarea>
</body>
</html>

Example 10.21 – Sort a List of Numbers Copy example 10.21 to the clipboardOpen example 10.21 in your browserDownload example 10.21 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Sort Interest</title>

<script>
/* Input: No user input
 * Processing: Test the built-in JavaScript sort function
 * Output: The contents of an array before it is
 *     sorted, and the contents after it is sorted.
 */
function testSort() {
    let numbers = [7, 10, 8, 16, 3, 35];
    document.getElementById('output').innerHTML = numbers + '<br>';
    numbers.sort(compareNumbers);
    document.getElementById('output').innerHTML += numbers;
}

// Compares two numbers by subtracting the second
// from the first which will return a negative
// number if the first number should be placed
// before the second, a zero if the two numbers
// are equal, and a positive number if the first
// number should be placed after the second.
function compareNumbers(x, y) {
    return x - y;
}
</script>
</head>

<body>
<button type="button" onclick="testSort()">Sort an Array</button>
<div id="output"></div>
</body>
</html>

Chapter 11. Objects

Example 11.8 – Dictionaries Copy example 11.8 to the clipboardOpen example 11.8 in your browserDownload example 11.8 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Student ID to Name</title>
<script>
// The values in this dictionary can be hard coded
// into a program or even better, they can be read
// from a file or database.
let students = {
    '07-153-4276' : 'Felix',
    '34-513-3186' : 'Jonathan',
    '26-430-0198' : 'Grace'
};


/* Input: a student's ID
 * Processing: find the student's name
 * Output: the student's name
 */
function findName() {
    // Get the student's ID.
    let studID = document.getElementById('studID').value;

    // Find the student's name in
    // the dictionary of students.
    let name = students[studID];
    if (!name) {
        // The student ID that the user entered
        // is not stored in the students dictionary.
        name = 'No such student ID';
    }

    // Display the student's name for the user to see.
    document.getElementById('output').innerHTML = name;
}
</script>
</head>

<body>
Student ID: <input type="text" id="studID">
<button type="button" onclick="findName()">Name</button>
<div id="output"></div>
</body>
</html>

Example 11.9 – Local Storage Copy example 11.9 to the clipboardOpen example 11.9 in your browserDownload example 11.9 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Local Storage Demo</title>
<script>
/* Saves the user's name to local storage. */
function saveName() {
    let name = document.getElementById('name').value;
    localStorage.name = name;
}


/* Loads the user's name from local storage. */
function loadName() {
    let name = localStorage.name;
    document.getElementById('name').value = name;
}


/* Builds and shows a message to a user. */
function showMessage() {
    // Get the user's name from the text field.
    let name = document.getElementById('name').value;

    // Build a message for the user.
    let message;
    if (name == "") {
        message = 'Please enter your name.';
    }
    else {
        message = 'Hello ' + name +
                '. I hope you have nice day.';
    }

    // Display the message for the user to see.
    document.getElementById('output').innerHTML = message;
}
</script>
</head>

<body>
Name: <input type="text" id="name">
<button type="button" onclick="loadName()">Load</button>
<button type="button" onclick="saveName()">Save</button><br>
<button type="button" onclick="showMessage()">Message</button>
<div id="output"></div>
</body>
</html>

Example 11.10 – Document Object Model Copy example 11.10 to the clipboardOpen example 11.10 in your browserDownload example 11.10 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Changing Text Fields</title>
<script>
/* Adds a text field at the end of the body. */
function addTextField() {
    // Create a unique identifier for the new text field.
    let texts = document.getElementsByTagName('input');
    let id = 'text' + texts.length;

    // Create a text field and set its id.
    let text = document.createElement('input');
    text.type = 'text';
    text.id = id;

    // Create a div and add the text field to the div.
    let div = document.createElement('div');
    div.appendChild(text);

    // Add the div to the document body.
    document.body.appendChild(div);
}


/* Changes the color of one text field. */
function changeColor() {
    let colors = [
        'black', 'gray', 'brown', 'blue',
        'purple', 'red', 'green', 'chartreuse',
        'yellow', 'orange', 'fuchsia', 'white'
    ];

    // Get an array of all text fields.
    let texts = document.getElementsByTagName('input');
    if (texts.length > 0) {

        // Choose a background and a foreground color.
        let index = choose(colors);
        let opposite = colors.length - index - 1;
        let background = colors[index];
        let foreground = colors[opposite];

        // Choose a text field.
        let text = texts[choose(texts)];

        // Change the element's colors.
        text.style.color = foreground;
        text.style.backgroundColor = background;
        text.value = foreground + ' on ' + background;
    }
}


/* Changes the size of all text fields. */
function changeSize() {
    // Get an array of all text fields.
    let texts = document.getElementsByTagName('input');
    if (texts.length > 0) {

        // Get the size of the first element.
        let size = texts[0].size;

        // Increment the size.
        if (++size > 30) {
            size = 5;
        }

        // Change the size of all text fields.
        for (let i = 0;  i < texts.length;  i++) {
            let text = texts[i];
            text.size = size;
        }
    }
}


/* Removes a pseudo randomly chosen text field. */
function removeTextField() {
    // Get an array of all text fields.
    let texts = document.getElementsByTagName('input');
    if (texts.length > 0) {

        // Choose a text field.
        let index = choose(texts);
        let text = texts[index];

        // Get the text field's parent.
        let div = text.parentElement;

        // Remove the parent and the text field.
        document.body.removeChild(div);

        // Renumber the id's of the remaining text fields.
        for (let i = index;  i < texts.length;  i++) {
            let id = 'text' + i;
            texts[i].id = id;
        }
    }
}


/* Returns a pseudo random integer
 * in the range [0, list.length). */
function choose(list) {
    let index = Math.floor(Math.random() * list.length);
    return index;
}
</script>
</head>

<body>
<button type="button" onclick="addTextField()">Add</button>
<button type="button" onclick="changeColor()">Color</button>
<button type="button" onclick="changeSize()">Size</button>
<button type="button" onclick="removeTextField()">Remove</button>
</body>
</html>

Chapter 12. Strings

Example 12.14 – Transpose Chords Copy example 12.14 to the clipboardOpen example 12.14 in your browserDownload example 12.14 to your computer

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta name="author" content="Rex Barzee">
<title>Transpose</title>

<script>
/* Input: Chord names and an integer
 * Processing:
 *     A loop that repeats once for each chord
 *         Transpose the chord
 *         Append the transposed chord onto an output string.
 * Output: The transposed chords
 */
function transposeAll() {
    // Get the chord names entered by the user as a string.
    let input = document.getElementById('chords').value;

    // Split the string into an array of chord names.
    let chords = input.split(', ');

    // Get the number of half steps to transpose the chords.
    let halfSteps = parseInt(
            document.getElementById('halfSteps').value);

    let sep = '';
    let output = '';
    for (let i = 0;  i < chords.length;  ++i) {
        // Retrieve one chord from the array of chords.
        let chord = chords[i];

        // Transpose one chord.
        let transposed = transposeChord(chord, halfSteps);

        // Append the transposed chord to the output.
        output += sep + transposed;
        sep = ', ';
    }

    // Display the transposed chords for the user to see.
    document.getElementById('output').innerHTML = output;
}


/* Parameters:
 *     chord - a string that is a chord name.
 *         Ex: D, Eb, Cm, A7, Fmaj7
 *     halfSteps - an integer that is the number
 *         of half steps to transpose the chord
 * Processing:
 1. Separate the chord name into a note name and a suffix.
 2. Find the index of the original note name.
 3. Transpose the note name by adding the half steps to the index.
 4. Normalize the index so that it is between 0 and 11, inclusive.
 5. Use the index to find the transposed note name.
 6. Combine the transposed note name and suffix into a chord name.
 * Return: The transposed chord name
 */
function transposeChord(chord, halfSteps) {
    // An array that contains all 12 note names in keyboard order.
    let notes = [
        'A', 'Bb', 'B', 'C', 'C#', 'D',
        'Eb', 'E', 'F', 'F#', 'G', 'Ab'
    ];

    // Separate the note name and suffix from the chord name.
    let note = getNote(chord);
    let suffix = getSuffix(chord);

    // Find where the note name is stored
    // in the array of all 12 note names.
    let index = notes.indexOf(note);

    // Transpose the original note by adding the half steps.
    index += halfSteps;

    // If the half steps value is negative and the
    // transposed index is less than 0, then repeatedly
    // add 12 to the index until it is non-negative.
    while (index < 0) {
        index += notes.length;
    }

    // If the half steps value is positive and the
    // transposed index is 12 or greater, then repeatedly
    // subtract 12 from the index until it is less than 12.
    while (index >= notes.length) {
        index -= notes.length;
    }

    // Build the transposed chord name by concatenating
    // the transposed note name to the chord suffix.
    let transposed = notes[index] + suffix;

    return transposed;
}


/* Parameter: chord - a string that is a chord name.
 *     Ex: D, Eb, Cm, A7, Fmaj7
 * Processing: Extract a substring from the chord name.
 * Return: the note name from the chord.
 *     Ex: D, Eb, C, A, F
 */
function getNote(chord) {
    let len = 1;
    if (chord.length > 1 && (chord[1] == 'b' || chord[1] == '#')) {
        len = 2;
    }
    let note = chord.substr(0, len);
    return note;
}


/* Parameter: chord - a string that is a chord name.
 *     Ex: D, Eb, Cm, A7, Fmaj7
 * Processing:
 *     Get the note name from the chord name.
 *     Extract a substring from the chord name.
 * Return: the suffix from the chord. Ex: m, 7, maj7
 */
function getSuffix(chord) {
    let note = getNote(chord);
    let suffix = chord.substr(note.length);
    return suffix;
}
</script>
</head>

<body>
Chords <input type="text" id="chords" size="30"><br>
Half steps <input type="text" id="halfSteps" size="2"><br>
<button type="button" onclick="transposeAll()">Transpose</button>
<div id="output"></div>
</body>
</html>

Further Reading

Front cover of Programming Fundamentals in JavaScript

All the example programs in this article came from the book Programming Fundamentals in JavaScript.