CMPS 335 Advanced Web Publishing JavaScript Programming


JavaScript Basics

Variables

Variable Names

Variables are named memory locations used to store data.  The following rules should be followed in naming variables: Examples:
Variable Declarations

JavaScript programmers typically use variables without declaring them.  However, it is a good practice to explicitly declare variables with the var keyword.  You can also assign a value to a variable at declaration or later in the script as shown in the following examples:
Variable Data Types

The values or data contained in variables can be classified by categories known as data types.  JavaScript has three data types: Examples:
    employeeName = "Mary";  // String
    totalNumber = 15;       // Integer number
    PayRate = 8.25;         // Floating-point number
    overTime = true;        // Boolean
    employeeNumber = null;  // null  
The null value is a data type as well as a value that can be assigned to a variable.  A variable with a null value is a defined variable with an empty value.  An undefined variable has not been declared and it does not exist.


Operators

There are many different groups of operators.  Operators also have order of precedence.  The grouping operator ( ) has the highest precedence.  It is followed by unary NOT operator !, arithmetic operators, comparison operators, and logical operators in the order presented below.  When operators of equal precedence are encountered, evaluation goes from left to right.

Arithmetic Operators Comparison Operators Logical Operators Assignment Operators Increment and Decrement Operators If a variable is incremented by 1, the increment operator ++ can be used.  If a variable is decremented by 1, the decrement operator -- can be used.  An increment operator or decrement operator can be placed either before or after a variable as shown in the following examples:
JavaScript Syntax Rules

JavaScript has its own rules of the language.  The following is some of these syntax rules:
Placement of a JavaScript Script
JavaScript Escape Sequences
     Escape Sequence    Character
   -------------------------------------------
      \n                New line
      \r                Carriage return
      \t                Horizontal tab
      \'                Single quotation mark
      \"                Double quotation mark
      \\                Backslash 

Functions

To make it easier for you to organize your scripts, JavaScript supports functions.  A function is a group of JavaScript statements that performs a task.  It is a reusable code that can be used as many times as needed simply by referring to the function's name.  Making use of a function is referred to as calling the function.  A function may have operands called parameters, also known as arguments.  Arguments are enclosed in parentheses and are separated by commas if there are more than one.  Functions can also return a value.  A function must be defined before it can be called.   The function definition should be placed within the <head> section.  Function calls are placed in the <body> section.

An event handler is a function that executes in response to a specific event such as the mouse click and the document load.  A method is a predefined function that belongs to a JavaScript object to act on the object's properties.

Global and Local Variables

A global variable is one that is declared outside of a function and it can be used anywhere in the program, even within functions.   A local variable is declared inside a function and can only be used within the function in which it is declared.  Local variables cease to exist when the function ends.  When you declare a global variable, the use of the var keyword is optional.  It is, however, a good practice to always use the var keyword

Built-In Fuctions

     Function          Descritption
    ------------------------------------------------------------
     parseInt( )    Evaluates a string and return an integer
     parseFloat( )  Evaluates a string and returns a real number

Basic Format for Coding HTML with JavaScript

JavaScript code contained inside a SCRIPT element is executed as the HTML document is loaded.  Any output the code generates is inserted into the document at the place the SCRIPT occurred.  One of the simplest way to display information is the document.write statement.  The following is the basic format for an HTML document with JavaScript:

The <script> tag identifies the script section in the document.  The language attribute specifies the scripting language.  This attribute is deprecated but often used.  The type attribute provides the script MIME type.  The script section can also include the src attribute to specify the location of an external script and the <noscript>...</noscript> tag pair to provide information for a browser that is not JavaScript-capable.

Communication between JavaScript and Users

JavaScript provides three Window methods that create dialog boxes for communicating with users.  These message boxes are described below: The default object for JavaScript is the Window object currently being displayed, so calls to these methods need not include an object reference.
Dispay Alert/Confirm windows

Examples
Example 1:
     <body>
     <h1>First JavaScript Page</h1>
     <script language="JavaScript">
     <!--
     document.write("Hello World");     //the write method
     // -->
     </script>
     </body>  
Example 2:
     <html>
     <head><title>Hello World JavaScript</title>
     <script language=JavaScript>
     <!--
     /* Function definition */
     function Average(a,b) {            // dummy arguments
     result = (a + b) / 2;            
     return result;
     }
     // -->
     </script>
     </head>
     <body>
     <br><h2 align=center>Welcome to JavaScript Programming!</h2>
     <script language="JavaScript">
     <!--
     window.alert("Do you want to\n compute the average?");
     /* Function call  */
     ave = Average(78,94);              // actual arguments
     document.write("<br><h2 align=center>Average of 78 and 94 
         is " + ave +"</h2>");
     // -->
     </script>
     <br>CMPS 491 Advanced Web Publishing
     </body>
     </html>  
Example 3:
     <html>  
     <head><title>Hello World JavaScript</title>
     </head>
     <body>
     <br><h2 align=center>Welcome to JavaScript Programming!</h2>
     <script language="JavaScript">
     <!--
       var number1, number2, num1, num2, ave
       window.alert("Do you want to\n compute the average?");
       number1 = window.prompt("Enter first integer", "0");
       number2 = window.prompt("Enter second integer", "0");
       num1 = parseInt( number1 );
       num2 = parseInt( number2 );
       ave = (num1 + num2) /2;
       document.write("<h2 align=center>Average of " + num1 +  
         " and " + num2 + "<br>is "+ ave + "</h2>");
       // -->
       </script>
       </body>
       </html>   

Online Example 1
Online Example 2

Testing and Debugging the Script

To test your script, simply load the HTML document in a Web browser either with or without network.  If there are errors, error messages may be displayed in the JavaScript Console (JavaScript 1.3 and Netscape 4.5 and later).  To display the console, type javascript: into the browser's Location box.

Return to CMPS 491 Home Page
Return to Web Site Home Page