CS 131       Fall 1998

Lab 1: JavaScript Basics

In this lab, you will explore some of the basic features of the JavaScript environment. In particular, you will write code and execute it in the JavaScript interpreter, and locate information in the JavaScript reference pages provided. You will also work with the Text Editor to save copies of your code and print a listing for submission with the Lab.

One of the overriding themes of this course is that programming is not an end to itself, but a tool for experimentation and problem-solving. As an example of this, you will consider several experiments with random word generation, using JavaScript as a tool in your analysis.


The JavaScript Environment

For the first part of this course, you will be writing your JavaScript code and executing it in the JavaScript Interpreter, which is accessible via a link on the class Web page (on the red strip to the left). Clicking on this link opens a window that contains a text box where you will enter your code. When you click on the Execute Code button on the right, the code that you entered will be executed and the resulting output will appear below.

For example, if you entered the following JavaScript code in the text box

document.write("Welcome to your first lab!"); and then clicked on the Execute Code button, the message Welcome to your first lab! would appear below.


When entering your code, you are free to use the arrow keys to move around and the backspace key to erase erroneous code. To erase an entire section of code, you can highlight the code (hold down the left mouse button and drag the cursor over the section of code) and then hit backspace. Note that if there are errors in your code, you can always go back and fix them and try again. The contents of the text box persist after executions, so you can repeatedly edit and execute the same piece of code.


EXERCISE 1:     As we mentioned in Lesson 1, programming languages such as JavaScript tend to be very picky with respect to the form in which instructions can be written. Not surprisingly, misspelling a command will usually cause an error. For example, misspelling document in the write statement above will cause an error message to appear on execution. However, JavaScript is not entirely inflexible, as there is some leeway in the form that statements can be written. For example, spaces (and tabs) are allowed in certain places.

For each of the following alterations to the write statement above, note whether the result is an error. That is, make the specified modification and attempt to execute the statement in the JavaScript interpreter. If an error occurs, try to explain why you think it occurred. If there is no error, note whether the displayed message is changed in any way.


Based on these examples, generalize as to when capitalization and spaces are allowed, and what their effect is in JavaScript statements such as this one.











EXERCISE 2:     Within the JavaScript environment, there are several reference documents to help you in learning how to program. Under the heading Quick References on the red strip to the left of the class page, there are several links directly relevant to this course.

  1. The How-to Basics: tasks such as logging in, starting up Netscape, ...
  2. The JavaScript Language: a quick outline of the JavaScript language, with examples
  3. The Turtle Graphics: routines relevant to Turtle Graphics (for later use in the course)
  4. The Lesson Summaries: summaries of the contents of all of the Online Lessons

While you do not know much about JavaScript yet, you can still get some practice accessing these pages. Search the JavaScript Language reference page to answer the following questions:


At the bottom of the class links are two links labeled JavaScript Guide and JavaScript Reference. These links will take you to the official documentation for JavaScript maintained by Netscape, providing detailed descriptions of the JavaScript language and its features. You may explore these documents at your leisure throughout the course. Clearly, there is much more to the JavaScript language than we are going to cover in one semester. However, the subset of JavaScript that you will be learning is sufficient for solving many challenging and interesting problems. You are certainly encouraged to push the limits of your knowledge via these documents.



EXERCISE 3:     While you are not expected to understand the following piece of JavaScript code, it can be executed to generate random 3-letter sequences. Type this code (exactly as it appears below) into the JavaScript interpreter. When you are done typing and attempt to execute it, don't be surprised if you get a syntax error or two. Chances are that you made a few typographical errors that will have to be fixed. The syntax error messages are usually pretty helpful in identifying and correcting such errors.

LETTERS = "abcdefghijklmnopqrstuvwxyz"; SIZE = 3; sequence = ""; for (i = 1; i <= SIZE; i++) { index = Math.floor(Math.random() * LETTERS.length); sequence = sequence + LETTERS.charAt(index); } document.write(sequence);

Once you have your code debugged (the computer term for error-free), execute it five times and list the letter sequences that were generated.






The Text Editor

In order to save your code so that you can reload and execute it in the future, you will need to use a text editor. If you are working in your dorm room, or at any other outside location, you can use whatever text editor is handy. On the computers in South 4, there is a simple text editor available under the Personal Applications menu. By clicking on its icon, you will open an editor window containing a blank document. As you write and test code in the JavaScript interpreter, you can save it by copying-and-pasting it into this document. (To copy-and-paste, highlight the contents of the text box and hit Alt-C, then place the cursor in the text editor document and hit Ctrl-V.) You can also copy-and-paste from the text editor into the JavaScript interpreter by highlighting the text in the editor and pressing Ctrl-C and then placing the cursor in the interpreter and pressing Alt-V. (Notice that the Alt key is used in the interpreter and the Ctrl key is used in the editor.)

To save a document in the Text Editor, select save under the File menu. You will be prompted for a file name, and the contents of the document will then be saved under that name. Once you have saved the document, a document icon with that name should appear in the File Manager window. To reopen that document at a future time, you can simply double click on the icon, or else select Open from the File menu in the Text Editor.


EXERCISE 4:     Cut-and-paste your code from the JavaScript interpreter and save it in a document called Lab1. Be sure to write your name, the name of the document, and today's date at the top of the document.




Problem-solving Using JavaScript

You are now prepared to use the JavaScript code to perform some experiments with random letter sequences. In particular, you will use this code as a tool for verifying or disproving hypotheses about word distributions, and to generate further data for analysis.

First, consider the total number of unique 3-letter sequences that can be generated. Since each of the three positions in the sequence can be any of the 26 letters, there are 263 = 17,576 different sequences. Clearly, not all of these sequences form real words. The question arises: how many random 3-letter sequences would you expect to have to generate before you obtain a word? Or, in JavaScript terms, how many times would you have to execute your code before a word is displayed?

It so happens that there are roughly 550 3-letter words in the English language (at least according to the UNIX online dictionary). Thus, if you generated a random 3-letter sequence, there is a 550 out of 17,576 chance that it will be a word. Since 550/17,567 is approximately 1/32, you should get a word 1 out of every 32 or so times. In other words, you would have to generate approximately 32 random 3-letter sequences to obtain a word. This number can be verified experimentally using your JavaScript code.


EXERCISE 5:     Execute your code repeatedly, counting the number of executions until you obtain a word. Do this 5 separate times and list the number of executions needed for each word. Do your experimental results support the theoretical prediction of 32 executions per word? If not, can you explain why?









As the length of the letter sequences increases, the chances of generating a word at random decreases dramatically. For example, there are 1,777 4-letter words in the online dictionary. Thus, the chances of generating a 4-letter word at random are 1 in 257 (264/1,777 = 456,976/1,777 = 257). For 5-letter sequences, the chances of generating a word at random is 1 in 4,920 (265/2,415 = 11,881,376/2,415 = 4,920) .

Part of the blame for the scarcity of words among randomly generated sequences falls on letters such as 'q' and 'z'. Since these letters are used so infrequently in English, their inclusion in a random sequence of letters makes a real word extremely unlikely. If we exclude letters such as these, however, we can improve the chances of generating words considerably. For example, the 10 letters that appear most frequently in English text are "etaoinshrd". Random sequences of these letters would appear more likely to produce words.


EXERCISE 6:     Your JavaScript code can be modifed to utilize only a subset of the alphabet by changing the sequence of letters in the first line, e.g., LETTERS = "etaoinshrd"; Modify your code to to use only these 10 letters, and execute the modified code 5 times. List the resulting 3-letter sequences below.





EXERCISE 7:     Similar to EXERCISE 5, execute your modified code repeatedly, counting the number of executions until you obtain a word. Do this 5 separate times and list the number of executions needed for each word.





EXERCISE 8:     Using your experimental results from the previous exercise, you should now be able to estimate the number of 3-letter words in the English language that use only the letters in "etaoinshrd". The following general formula applies: # of words = (# of sequences) * (chances that a random sequence is a word) The total number of 3-letter sequences that use only 10 letters is 103 = 1,000. As an approximation of the chances that a random sequence of these letters is a word, take 1 over the median (middle) of your numbers from the previous exercise. For example, suppose your experiments required 10, 20, 5, 15, and 25 executions, respectively, to obtain words. Since the median of these number is 15, you can estimate the chances of generating a word at random to be 1/15. Plugging these numbers into the above formula, the total number of 3-letter words using only "etaoinshrd" is estimated to be (1,000 * 1/15) = 67.

Show your work in obtaining your estimate.   Note: you can use the JavaScript interpreter to help in the computation, e.g.,

document.write( 1000 * (1/15) );









EXERCISE 9:     In addition to changing the letters used in random sequences, you can change the lengths of the sequences generated by the JavaScript code. For example, to generate 4-letter sequences, simply change the 3 to a 4 in the second line, i.e., SIZE = 4; Make this modification, and then use your program to estimate the number of 4-letter words that use only the letters "etaoinshrd". Show your work in obtaining your estimate.

























Cut-and-paste a copy of your modified code at the bottom of your Lab1 document, below the original version. Hand in a printout of your Lab1 file, attached to these sheets.