Programming with JavaScript

CS 102

Nov. 17, 2004

Introduction

In this lab, you'll get to examine a short program to see how one looks and what sorts of things a programmer can do with just a few lines of code. This will set the stage and give you some background for our later look at Artificial Intelligence.

Lab

  1. Look over the following program and try to predict what it will do. First, observe that the program is embedded within a Web page. The lines that begin with // are comments. They aren't a part of the program, just documentation for it.

    <html>
    <head>
    </head>
    <body>
    <script><!--
    // This is a comment.  You don't need to type-in any of these, except
    // for the one at the end.
    
    // Variable declarations.
    var name;
    var age;
    var i;
    var currentYear = 2004;
    var birthYear;
    var response;
    
    // Some straight-line execution.
    name = prompt("What is your name?", "");
    document.write("Hello " + name + "!<br><br>");
    
    age = prompt(name + ", how old are you?", "");
    
    // A conditional.
    if (age >= 30)
       document.write("We can't trust you!<br><br>");
    else
       document.write("I wish I were young again!<br><br>");
    
    birthYear = currentYear - age - 1;
    
    response = prompt("Were your born in " + birthYear + "? (y or n)", "");
    if (response == "y")
       document.write("I'm smart, aren't I?<br><br>");
    else
       document.write("You were born too early in the year!<br><br>");
    
    // A loop.
    for (i = 1; i <= age; i = i + 1)
        document.write(i + "<br>");
    
    document.write("<br>Goodbye " + name + "!<br>");
    
    // You need the following comment in your program.
    //-->
    </script>
    </body>
    </html>
    

  2. Using notepad, type the program in (you needn't type-in the comments, except for the final one). OR --- just copy & paste the code into notepad from the HTML version of the lab on the class Web page. This will save you time.

  3. Save the program onto your G: drive folder with the name jscript.htm.

  4. Open your G: drive folder and double-click on jscript.htm to run the program.

  5. Did it do what you expected it to? Try to reconcile your predicted behavior of the program with what it actually did.

  6. Challenges:
    1. Can you modify the for loop so that it counts by two rather than counting by one?

    2. Can you modify the for loop so that it counts backwards? (From your age down to 1.)



Thomas P. Kelliher
Tue Nov 16 08:26:02 EST 2004
Tom Kelliher