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:
- A variable name must begin with a letter, a dollar sign, or an
underscore.
- A variable name can include letters, digits, dollar sign, and
the underscore.
- A variable name can not contain a space.
- Variable names are case sensitive.
- Use friendly names whenever possible and avoid using JavaScript
reserved words.
Examples:
Valid names: totalDue, total_due, hourlyPayRate, name2, c,
$payRate, _pay_rate
Invalid names: @array1, %payRate, 2name, total due
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:
var employeeName = "John", idNumber = 4175, payRate;
var title1, title2;
payRate = 9.5;
title1 = "President";
Variable Data Types
The values or data contained in variables can be classified by
categories known as data types. JavaScript has three data types:
- Numeric: Integer numbers and floating-point numbers
- String: Alphanumeric text (enclosed in quotation marks)
- Boolean: A logical value (true or false)
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
- && (logical AND)
- || (logical OR)
Assignment Operators
Increment and Decrement Operators
- Increment operator +=
Examples: a += 5 is equivalnet to
a = a + 5 and a += 1 is equivalnet to a = a + 1.
- Decrement operator -=
Examples: a -= 5 is equivalnet to
a = a - 5 and a -= 1 is equivalnet to a = a - 1.
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:
- preincrement operator ++b
Increment b by 1,
then use the new value of b in the the expression in which
b resides.
- postincrement operator b++
Use the current value of
b in the expression in which b resides, then increment
b by 1.
JavaScript Syntax Rules
JavaScript has its own rules of the language. The following
is some of these syntax rules:
- All JavaScript scripts are enclosed within the <script> ...
</script> tag pair.
- A script may be enclosed inside an HTML comment tag
to hide the script from non-JavaScript browsers.
- JavaScript uses // for a one-line comment and /* ... */
for a multiline block comment.
- JavaScript is case sensitive. However, names of event handlers
are part of an HTML tag and they are not case sensitive.
- A JavaScript statement ends with a semicolon. A statement may span
several lines until it is ended by a semicolon.
Placement of a JavaScript Script
- In the <body> section of the HTML document
The output of the script is displayed as part of the Web page.
- Within the <header>...</header> tag pair
Functions are placed in this section.
- As an attribute within an HTML tag
An event handler is placed here without using the <script> tag.
- In a separate file with the .js extension
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:
.
. (Regular HTML)
.
<script language="JavaScript" type="text/javascript">
<!--
JavaScript code here
// -->
</script>
.
. (More regular HTML)
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:
window.alert( ): Displays a message and an OK button
window.confirm( ): Displays a message and two buttons (OK and Cancel)
window.prompt( ): Displays a message, a text box, and two buttons (OK
and Cancel)
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