JavaScript Tutorial for Programmers

JavaScript
is a object-based programming language for developing client-side interactive applications scripting. Program procedure can be embedded directly into an HTML page. processing can recognize and respond to user events such as mouse clicks, form input, and page navigation. For example, you can write a JavaScript function to verify that users enter valid information into a form. Without any network transmission, an HTML page with embedded JavaScript can interpret the entered text and alert the user with a message dialog if the input is invalid. Or you can use JavaScript to perform an action (such as play an audio file, execute an applet, or communicate with a plug-in) in response to the user opening or exiting a page.


Aaron Weiss July 12, 1998
There are several versions of JavaScript supported by certain browsers and browser versions. Unfortunately, this can often lead to confusion and incompatibilities. Since Netscape originally introduced JavaScript, JavaScript 1.0 was the language specification supported in Netscape Navigator 2.0. Subsequently, Navigator 3.0 supported new enhancements which comprised JavaScript 1.1. At present, Navigator 4.0 supports JavaScript 1.2. In parallel, Microsoft attempted to support JavaScript 1.0 in their Internet Explorer 3.0 browser. Known as "Jscript," Microsoft's initial JavaScript support was unreliable and buggy. A push to standardize the language resulted in an "official" version of JavaScript sanctioned by the ECMA. Internet Explorer 4.0 includes robust support for the ECMA standardized JavaScript, which, although it shares much in common with Netscape's JavaScript 1.2, is not exactly equivalent.

While programming for any single version of JavaScript is relatively simple, writing code which functions across disparate versions, most notably Navigator 4 or above and MSIE 4 or above, is one of the major challenges and topics of discussion in JavaScript programming at this time.

JavaScript code is typically embedded into an HTML document using the SCRIPT tag. You are free to embed as many scripts into a single document as you like, using multiple SCRIPT tags. A script embedded in HTML with the SCRIPT tag uses the format:

<script language="JavaScript">
<!--
document.write("Hello World!");
//-->
</script>

The LANGUAGE attribute is optional, but recommended. You may specify that a section of code only be executed by browsers which support a particular version of JavaScript; for instance:

<script language="JavaScript1.2">

Another attribute of the SCRIPT tag, SRC, can be used to include an external file containing JavaScript code rather than code embedded into the HTML:

<script language="JavaScript" src="corefunctions.js">
</script>

The external file is simply a text file containing JavaScript code, and whose filename ends with the extension ".js". Note that although some version 3 browsers support the SRC attribute, it only functions reliably across platforms in the version 4 browsers.

Scripts can be placed inside comment fields to ensure that your JavaScript code is not displayed by old browsers that do not recognize JavaScript. The markup to begin a comment field is <!-- while you close a comment field using //-->. This practice is certainly optional, but considered good form when your page is likely to be visited by older browsers. Certainly, as older browsers fade away, this practice will likely become unnecessary.

JavaScript code, much like other programming languages, is made up of statements which serve to make assignments, compare values, and execute other sections of code. By and large, programmers will already be familiar with JavaScript's usage of variables, operators, and statements. Below is a chart summarizing the main elements of JavaScript grammar. Following, we will look at each element in detail.

Variables

Labels which refer to a changeable value.
Example: total may be possess a value of 100.

Operators

Actors which can be used to calculate or compare values.
Example: Two values may be summed using the addition operator (+); total+tax
Example: Two values may be compared using the greater-than operator (>); total>200

Expressions

Any combination of variables, operators, and statements which evaluate to some result. In English parlance this might be termed a "sentence" or even a "phrase", in that grammatical elements are combined into a cogent meaning.
Example: total=100;
Example: if (total>100)

Statements

As in English, a statement pulls all grammatical elements together into a full thought. JavaScript statements may take the form of conditionals, loops, or object manipulations. It is good form to separate statements by semicolons, although this is only mandatory if multiple statements reside on the same line.
Example: if (total>100) {statements;} else {statements;}
Example: while (clicks<10) {statements;}

Objects

Containing constructs which possess a set of values, each value reflected into an individual property of that object. Objects are a critical concept and feature of JavaScript. A single object may contain many properties, each property which acts like a variable reflecting a certain value. JavaScript can reference a large number of "built-in" objects which refer to characteristics of a Web document. For instance, the document object contains properties which reflect the background color of the current document, its title, and many more. For a fuller explanation of the built-in objects of JavaScript, see the section on "Document Object Model".

Functions and Methods

A JavaScript function is quite similar to a "procedure" or "subroutine" in other programming languages. A function is a discrete set of statements which perform some action. It may accept incoming values (parameters), and it may return an outgoing value. A function is "called" from a JavaScript statement to perform its duty. A method is simply a function which is contained in an object. For instance, a function which closes the current window, named close(), is part of the window object; thus, window.close() is known as a method.

 

Variables store and retrieve data, also known as "values". A variable can refer to a value which changes or is changed. Variables are referred to by name, although the name you give them must conform to certain rules. A JavaScript identifier, or name, must start with a letter or underscore ("_"); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). Typically, variable names are chosen to be meaningful regarding the value they hold. For example, a good variable name for containing the total price of goods orders would be total.

Scope

When you assign a new variable to an initial value, you must consider the issue of scope. A variable may be scoped as either global or local. A global variable may be accessed from any JavaScript on the page. A local variable may only be accessed from within the function in which it was assigned. Commonly, you create a new global variable by simply assigning it a value:
newVariable=5;
However, if you are coding within a function and you want to create a local variable which only scopes within that function you must declare the new variable using the var statement:
function newFunction()
{ var loop=1;
  total=0;
  ...additional statements... 
}
In the example above, the variable loop will be local to newFunction(), while total will be global to the entire page.

Type

A value, the data assigned to a variable, may consist of any sort of data. However, JavaScript considers data to fall into several possible types.
Depending on the type of data, certain operations may or may not be able to be performed on the values. For example, you cannot arithmetically multiply two string values. Variables can be these types:

Numbers

3 or 7.987, Integer and floating-point numbers.

  • Integers can be positive, 0, or negative; Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7.
  • A floating-point number can contain either a decimal point, an "e" (uppercase or lowercase), which is used to represent "ten to the power of" in scientific notation, or both. The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").

Booleans

True or False. The possible Boolean values are true and false. These are special values, and are not usable as 1 and 0. In a comparison, any expression that evaluates to 0 is taken to be false, and any statement that evaluates to a number other than 0 is taken to be true.

Strings

"Hello World !" Strings are delineated by single or double quotation marks. (Use single quotes to type strings that contain quotation marks.)

Objects

myObj = new Object();

Null

Not the same as zero - no value at all. A null value is one that has no value and means nothing.

Undefined

A value that is undefined is a value held by a variable after it has been created, but before a value has been assigned to it.

That said, JavaScript is a loosely typed language -- you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. By and large, you may simply assign any type of data to any variable. The only time data typing matters is when you need to perform operations on the data. Certain operators behave differently depending on the type of data being deal with. For example, consider the + operator:

"5" + "10"

yields

"510" (string concatenation)

5 + 10

yields

15 (arithmetic sum)

Operators take one or more variables or values (operands) and return a new value; e.g. the '+' operator can add two numbers to produce a third. You use operators in expressions to relate values, whether to perform arithmetic or compare quantities. Operators are divided into several classes depending on the relation they perform:

arithmetic or computational

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are:

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus: the remainder after division;
e.g. 10 % 3 yields 1.
++ Unary increment: this operator only takes one operand. The operand's value is increased by 1. The value returned depends on whether the ++ operator is placed before or after the operand; e.g. ++x will return the value of x following the increment whereas x++ will return the value of x prior to the increment.
-- Unary decrement: this operator only takes one operand. The operand's value is decreased by 1. The value returned depends on whether the -- operator is placed before or after the operand; e.g. --x will return the value of x following the decrement whereas x-- will return the value of x prior to the decrement.
- Unary negation: returns the negation of operand.

Comparison

A comparison operator compares its operands and returns a logical value based on whether the comparison is true or not. The operands can be numerical or string values. When used on string values, the comparisons are based on the standard lexicographical (alphabetic) ordering.

== "Equal to" returns true if operands are equal.
!= "Not equal to" returns true if operands are not equal.
> "Greater than" returns true if left operand is greater than right operand.
>= "Greater than or equal to" returns true if left operand is greater than or equal to right operand.
< "Less than" returns true if left operand is less than right operand.
<= "Less than or equal to" returns true if left operand is less than or equal to right operand.

Boolean

Boolean operators are typically used to combine multiple comparisons into a conditional expression. For example, you might want to test whether (total>100) AND (stateTax=true). A boolean operator takes two operands, each of which is a true or false value, and returns a true or false result.

&& "And" returns true if both operands are true.
|| "Or" returns true if either operand is true.
! "Not" returns true if the negation of the operand is true (e.g. the operand is false).

String

Strings can be compared using the comparison operators. Additionally, you can concatenate strings using the + operator.

"dog" + "bert"

yields

"dogbert"

Assignment

The assignment operator (=) lets you assign a value to a variable. You can assign any value to a variable, including another variable (whose value will be assigned). Several shorthand assignment operators allow you to perform an operation and assign its result to a variable in one step.

= Assigns the value of the righthand operand to the variable on the left.
Example: total=100;
Example: total=(price+tax+shipping)
+=
(also -=, *=, /=)
Adds the value of the righthand operand to the lefthand variable and stores the result in the lefthand variable.
Example: total+=shipping (adds value of shipping to total and assigned result to total)
&=
(also |=)
Assigns result of (lefthand operand && righthand operand) to lefthand operand.

Special

Several JavaScript operators, rarely used, fall into no particular category. These operators are summarized below.

Conditional operator

(condition) ? trueVal : falseVal

Assigns a specified value to a variable if a condition is true, otherwise assigns an alternate value if condition is false.
Example:
preferredPet = (cats > dogs) ? "felines" : "canines"

If (cats>dogs), preferredPet will be assigned the string value "felines," otherwise it will be assigned "canines".
typeof operand Returns the data type of operand.
Example -- test a variable to determine if it contains a number:
if (typeof total=="number") ...

Regular expressions (Netscape & MSIE 4)

New to JavaScript 1.2 is support for regular expressions, which are defined patterns used to match character combinations appearing in string values. Regular expressions are very powerful, potentially allowing you to search for any conceivable character pattern. However, they can also be quite complex to construct. Because regular expressions are widely supported in all high-level development environments, it is advised that you consider learning about regular expressions as a subject unto itself.

Two detailed explanations of regular expressions can be found at










 
 Privacy Statement | Disclaimer | Copyrights © 2004, Wingck'C Web Technologies. All Rights Reserved open source of GNU