Computer Languages

JavaScript

[ Back to Lecture Notes ] [ JavaScript Number I/O ] [ QBasic ]
Interpreted Program Translation
JavaScript SCRIPT tag
Statements, Expressions, & Variables
Data Types and Operators
Input and Output
Conditional Control Statements
Iteration (Loops)
Convert Number Bases
Where to Next?
Example Source Code

Interpreted Program Translation

An interpreted computer language is a high-level language that is translated into binary machine code each time it is read from a source file. Disadvantages of interpreted languages are mainly that there is a translation time penalty each time the program is run, and the language interpreter must be present on each computer that will run the program. However, as a development tool interpreted languages are useful because a program prototype can be written and tested quickly, and since most interpreters step through the program line by line errors are easily localized and identified. Since most assemblers and compilers have a steep learning curve just to master the development environment interpreters are also ideal as learning tools.

CIS 120 and 121 are about computer concepts in general, not about programming in particular. With that in mind only the very essential JavaScript statements, functions, and operators will be used. Recall that, as a minimum, we want a program to organize data, calculate results, and present the results. We will be looking at ways JavaScript can get user input, manipulate the input (data), control program flow as needed, and produce output useful to the user. Consult the Resources Page for links to online JavaScript help and tutorials.

[ TOP ]

JavaScript SCRIPT tag

While JavaScript and QBasic are both interpreted languages, the similarity pretty much ends there. JavaScript is a member of the "C family" of languages; the syntax is very C-like and it inherits a lot of the "C/C++ philosophy." JavaScript does not have its own editor and environment like QBasic; JavaScript's environment is an HTML document and a web browser. You write JavaScript code directly in your HTML files between tags like this:

    <script type="text/javascript">

        // JavaScript code goes here

    </script>

There are 2 types of comments in JavaScript. Also, it is common to see JavaScript examples that use a special comment idiom to hide the script from browsers that cannot interpret JavaScript. If there is a chance a viewer might not be able to see your script you can also use the <NOSCRIPT> element to let them know they are missing part of your page (they might have disabled script support on their browser):

    <script type="text/javascript">
    <!-- HTML style comment hides script from old browsers>

        /* JavaScript code goes here ...
           This is a multi-line comment */

        // This is a single-line comment

    // JavaScript style comment ends hiding comment -->
    </script>

    <noscript>

        This page requires a browser that supports JavaScript
        <!-- note that this is HTML, not JavaScript -->

    </noscript>

Like other "C-family" languages, JavaScript is case sensitive ; the following are completely different variables, and IF is not recognized as a keyword:

    Count = 10;
    IF ( count < 10 ) {    // Error! IF is not a keyword
        // do something...
    }
[ TOP ]

Statements, Expressions, & Variables

Statements and Expressions

Variables

[ TOP ]

JavaScript Data Types and Operators

JavaScript is a "loosely typed" language; unlike QBasic (and most compiled languages) you do not specify a data type. Essentially all variables are character strings and are interpreted out of context. Usually this is done correctly, but as will be shown, occasionally there are surprises. See JavaScript Number I/O for more details and sample solutions.

Operators

The arithmetic operators +, -, *,and / should be self explanatory. An operator that may be new to you that is supported in virtually all programming languages is the modulus division operator. Modulus division returns the remainder rather than the quotient. In JavaScript the modulus operator is %. This differs from QBasic which uses the MOD operator for modulus division; other languages, including some dialects of BASIC, use a function like MOD(n, m).

    a = 19 % 4              // a = 3; 19 divided by 4 leaves a remainder of 3
    b = 19 / 4              // b = 4.75; no "integer" type
    c = parseInt(19 / 4)    // c = 4; integer division

Modulus division is very useful for many problems in computers; think back to our procedure for converting a decimal number to binary or hexadecimal. We started with the highest power of the base that could be divided into our decimal number, then kept working down by dividing the remainder by each successive lower power of the base.

Logical conditions are tested with the familiar < and > symbols used in mathematics for "less than" and "greater than". "Less than or equal to" and "greater than or equal to" use the <= and >= operators respectively. Equality is tested with the == operator and inequality ( "not equal to" ) is tested with the != operator. This differs from QBasic which uses = for equality as well as assignment, and <> for inequality. In JavaScript the logical operators return a Boolean type, either true or false (named after 19th century mathematician George Boole).

    x = 3;
    y = 4;
    (x == y);   // returns false
    (x != y);   // returns true
    (x < y);    // returns true
    (y >= x);   // returns false

Assignment
The assignment operator is =

Precedence and Associativity

[ TOP ]

JavaScript Input and Output

For simple, "quick and dirty" input use the prompt() dialog for input and the document.write() method for output. Alternatively you can use the alert() or confirm() dialogs for output. The following JavaScript statements will prompt the user for a name and then issue a greeting using an alert() dialog:

    <!-- io1.htm -->
    <script type="text/javascript">
        name = prompt( "Enter your name: " );                       // get user name
        alert( "Hello, " + name + ", Welcome to CIS 121!"  );       // say hello
    </script>

Try the code

The prompt() method takes an optional default argument following the prompt string so that you can pre-load the prompt text entry box with a name or default variable value. It is common to use an "empty string" for the second argument so that the prompt dialog is simple empty. This example uses the document.write() method to write to the document:

    <!-- io2.htm -->
    <script type="text/javascript">
        name = prompt( "Enter your name: ", "" );                       // get user name
        document.write( "Hello " + name + ", welcome to CIS 121!" );    // say hello
    </script>

Try the code

The previous snippets are examples of an algorithm-driven or proceduralinterface: the application is active at all times; when the program gets to the place where input is required from the user it just sits and waits for input. A better model is event-driven where the application is passive; it waits for an event to occur, responds to the event, then waits for the next event. Applications with a Graphical User Interface (GUI) are typically event- driven.

    <!-- io3.htm -->
    <html>
    <head>
    <title>JavaScript Event-driven I/O Example</title>
    <script type="text/javascript">
    /*
     *  Event handler
     */
    function getName() {
        name = document.ioForm.inText.value;                    // get input
        outStr = "Hello " + name + ", Welcome to CIS 121!"      // build output string
        document.ioForm.outText.value = outStr;                 // output
    }
    </script>
    </head>
    <body>
    <!-- create a form for event-driven input and output -->
    <form name="ioForm">
        <p>                             <!-- input box and buttons -->
        Enter your name:<br />
        <input type="text" name="inText">
        <input type="button" value="Enter" onclick="getName();">
        </p>
        <p>                             <!-- output text box -->
        Output area:<br />
        <textarea name="outText" rows="5" cols="40"></textarea><br />
        <input type="reset">
        </p>
    </form>
    </body>
    </html>

Try the code

Notice that we cannot use document.write(); in fact we can only do a one-time copy of a single string to the output form element, so we "build" a string with the " + " operator.

[ TOP ]

Conditional Control Statements

Selection

The JavaScript control statement that allows a program to branch to different areas based on some condition is if . . . else if . . . else.

    <!-- if.htm -->
    <script type="text/javascript">
        <script type="text/javascript">
        order = prompt( "Total order? ", 0 );   // get amount spent
                                                    // default = 0
        if ( order < 100.0 ) {
            discount = order * 0.1;
        }
        if ( order >= 100.0 ) {
            discount = order * 0.15;                            // reward big spenders
        }

        document.write( "Discount = $", discount, "<BR>" );     // display results
    </script>

Try the code

What would happen if, instead of ( order >= 100.0 ) we wrote ( order > 100.0 ) in the example?
How would you test this program to ensure it worked correctly?

Note that HTML tags can be included in strings that are written to the document object; that is how line breaks are inserted. Unlike QBasic, the "if" statement does not have a corresponding "end if." If more than one statement is to be included in the if clause then braces ( "{" and "}" ) must enclose the entire block:

    if ( order < 100.0 ) {
        discount = order * 0.1;
        totalOrder = totalOrder - discount;
    }

You will also see the following coding style in many examples; it is also correct, just a matter of style:

    if ( order < 100.0 )
    {
        discount = order * 0.1;
        totalOrder = totalOrder - discount;
    }

And it is correct in JavaScript (and C, C++, and Java) to omit the curly braces for a single statement:

    if ( order < 100.0 )
        discount = order * 0.1;

However, I highly recommend always using braces. It is very easy to introduce subtle and hard to find bugs when you go back and decide to add another line to your if statement and forget to add braces. Ask me how I know . . .
Also, the Perl programming language uses similar syntax and requires the braces for single lines. Perl is becoming a de facto standard shell scripting language on UNIX systems and is used for server-side CGI scripting, so good habits developed early will pay off.

You can use "else" similar to QBasic, however note that there is no "elseif" keyword; it is really like there is only "else" followed by another "if" statement:

    <!-- ifelse.htm -->
        <script type="text/javascript">
        order = prompt( "Total order? ", 0 );   // get amount spent
                                                // default = 0
        if ( order < 100.0 ) {
            discount = order * 0.1;
        }
        else if ( order < 500.0 ) {
            discount = order * 0.15;
        }
        else {
            discount = order * 0.2;
        }
    </script>
[ TOP ]

Iteration (Loops)

Iteration

The JavaScript control statement we will use to repeat sections of code based on the value of a condition is the while loop. The other main looping construct in JavaScript is the for loop, and there is a do...while loop. However, all loops can be written with one basic form even if that one form is not always the clearest or most efficient. When first writing iterative statements (i.e. loops) pick one basic construct and get it right before trying other forms.

Here is a simple loop:

    <!-- loop1.htm -->
    <script type="text/javascript">
        // a simple loop
        i = 0;                          // loop index counter
        maxCount = 10;                  // number of times to repeat

        while ( i < maxCount ) {
            document.write( i, ", " );  // display value of loop index
            i = i + 1;                  // IMPORTANT! increment the index so
        }                               //   we don't get in an infinite loop
    </script>

Try the code

This next loop is a bit more involved; it prompts the user for a number and saves it in a variable called sum, then enters a loop where it prompts for another number to add to sum. Note how, before entering the loop, the answer variable is pre-loaded to force at least one pass through the loop. At the end of each loop the user is asked if she wants to continue. Note also how the response is converted to upper case to simplify the test for a "NO" answer.

    <!-- loop2.htm -->
    <script type="text/javascript">
        // add numbers until user says no
        sum = prompt( "Enter first number: ", 0 );  // get first number to get started

        answer = "Y";                               // assume user wants to continue
        while ( answer != "N" ) {                   // loop until user answers no
          n = prompt( "Enter next number: ", 0 );   // get next number
          sum = sum * 1 + n * 1;                    // add next number to sum
          document.write( "Sum = ", sum, "<BR>" );  // display the sum
          answer = prompt( "Continue? ", "Y" );     // add another number?
          answer = answer.toUpperCase();            // convert to upper case so only
        }                                           //   one char is tested
    </script>

Try the code [ TOP ]


Convert Number Bases

Here are some number conversions that take advantage of functionality built into some JavaScript number and math objects. Given the above examples and discussion see if you can suggest ways to make this program more functional.

    <!-- convert.htm -->
    <script type="text/javascript">
        binStr = "111011";
        hexStr = "CD";

        binNum = parseInt( binStr, 2 );
        hexNum = parseInt( hexStr, 16 );

        document.write( binStr + " = " + binNum + " Decimal, " );
        document.write( binNum.toString( 16 ) + " Hexadecimal<BR>" );

        document.write( hexStr + " = " + hexNum + " Decimal, " );
        document.write( hexNum.toString( 2 ) + " Binary<BR>" );
    </script>

Try the code [ TOP ]


Where to Next?

There are numerous online sources of information on JavaScript; I have listed a few tutorials on the Resources page. A good "no frills" coverage of the basics needed to get started with JavaScript is the Introduction to JavaScript from TrainingTools.com: http://www.trainingtools.com/online/javascript/index.htm If the link works, try the Netscape Client-Side JavaScript Documentation site, but be advised it is much less tutorial in nature. Also, see the Mozilla JavaScript site. The Coolnerds Electronic JavaScript Reference at http://www.sackeri.org/coolnerds/jscript/javaref.htm is good to look specifics about JavaScript functions and objects you want to use, or see just what is happening in code you are looking at.

Search the Web for JavaScript examples and samples; study what others have written and try to figure them out. Try to put a few short programs together to do something useful. The best way to learn a language, like learning to play a musical instrument, is to jump in and practice. However, unlike learning a new musical instrument, at least you won't annoy the neighbors or make the dog howl...

[ TOP ]

Example Source Code

Source code for examples in the order presented.

io1.htm
io2.htm
io3.htm
if.htm
ifelse.htm
loop1.htm
loop2.htm
asc_code.htm
convert.htm
[ TOP ]