| JavaScript reserved words | |||
|---|---|---|---|
| abstract | boolean | break | byte |
| case | catch | char | class |
| const | continue | debugger | default |
| delete | do | double | else |
| enum | export | extends | false |
| final | finally | float | for |
| function | goto | if | implements |
| import | in | instanceof | int |
| interface | long | native | new |
| null | package | private | protected |
| public | return | short | static |
| super | switch | synchronized | this |
| throw | throws | transient | true |
| try | typeof | var | volatile |
| while | with | ||
When you use the reserved word var to create a variable, you declare the varible. You can assign a value at declaration. Example:
var variable_name = value;
var firstVar = "text", secondVar = 100, thirdVar = 2.5;
var fourthVar; // fourthVar is undefined
var fifthVar = null; // null value
var sixthVar = ""; // null string
When you declare a variable without assigning it a value, you must use the var keyword. Its value is undefined.
The name of a variable is an identifier. Identifiers must begin with an uppercase or lowercase ASCII letter, dollar sign ($), or underscore (_). You can use numbers in an identifier, but not the first characters. Common practice: use a lowercase letter for the first letter of the first word in a variable name. Variable names are case-sensitive.
A global variable is one that is declared outside a function, or is declared without the var keyword, and is available to all parts of your program. A local variable is declared with the var keyword and inside a function and is only available within the function in which it is declared.
Example: Tutorial2VariableScopeEx1.html
<HTML>
<HEAD>
<TITLE>Tutorial 2: Variable Scope Example 1</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
firstGlobalVariable = "firstGlobalVariable";
var secondGlobalVariable = "secondGlobalVariable";
var thirdGlobalVariable;
function scopeExample() {
fourthGlobalVariable = "fourthGlobalVariable";
// Yes, this is a global variable, because of no var keyword
var localVariable = "localVariable";
document.writeln("scopeExample:
firstGlobalVariable = " + firstGlobalVariable + "<BR>");
document.writeln("scopeExample: secondGlobalVariable = " +
secondGlobalVariable + "<BR>");
document.writeln("scopeExample: thirdGlobalVariable =
" + thirdGlobalVariable + "<BR>");
document.writeln("scopeExample:
fourthGlobalVariable = " + fourthGlobalVariable + "<BR>");
document.writeln("scopeExample:
localVariable = " + localVariable + "<BR>");
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
thirdGlobalVariable = "thirdGlobalVariable";
scopeExample();
document.writeln("HTML BODY:
firstGlobalVariable = " + firstGlobalVariable + "<BR>");
document.writeln("HTML BODY: secondGlobalVariable = " +
secondGlobalVariable + "<BR>");
document.writeln("HTML BODY:
thirdGlobalVariable = " + thirdGlobalVariable + "<BR>");
document.writeln("HTML BODY:
fourthGlobalVariable = " + fourthGlobalVariable + "<BR>");
// document.writeln("HTML BODY: localVariable = " + localVariable +
"<BR>");
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</BODY>
</HTML>
Click here to see the output of Tutorial2VariableScopeEx1.html.
A function allows you to treat a related group of JavaScript statements as a single unit. The lines that compose a function within an HTML document are called function definition. The syntax for defining a function is:
function name_of_function(parameters) {
statements;
}
A function definition consists of three parts:
Example: Tutorial2FunctionEx1.html
<HTML>
<HEAD>
<TITLE>Tutorial 2: Function Example 1: add
function</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function add(parm1, parm2) {
var sum;
sum = parm1 + parm2;
return sum;
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
var sum, num1 = 5, num2 = 6.4;
sum = add(num1, num2);
document.writeln("The sum of " + num1 + " and " + num2 +
" is: " + sum);
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</BODY>
</HTML>
Click here to see the output of Tutorial2FunctionEx1.html.
| Built-in JavaScript function | |
|---|---|
| Function | Description |
| eval() | Evaluates expressions contained within strings |
| isFinite() | Determines whether a number is finite |
| isNaN(testValue) |
The isNaN function evaluates an argument to
determine if it is "NaN" (not a number). isNaN(testValue)testValue is the value you want to evaluate. On platforms that support NaN, the parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. isNaN returns true if passed "NaN," and false otherwise. |
| parseInt(str[, radix]) | Converts string literals to integers.
parseInt parses its first argument, the string str, and attempts to return an integer of the specified radix (base), indicated by the second, optional argument, radix. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used. If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The parseInt function truncates numbers to integer values. Radix : Optional. A value between 2 and 16 indicating the base of the number contained in str. If not supplied, strings with a prefix of '0x' are considered hexadecimal and strings with a prefix of '0' are considered octal. All other strings are considered decimal. In the absence of the radix (base) argument, parseInt will treat any string beginning with a zero as an octal number string - since neither 08 nor 09 is a valid octal number, it is returning 0 to indicate that it is unable to parse the character 8 and 9. |
| parseFloat(str) | Converts string literals to floating-point numbers.
parseFloat parses its argument, the string str, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number). |
| encodeURI() | Encodes a text string into a valid URI |
| encodeURIComponent() | Encodes a text string into a valid URI Component |
| decodeURI() | Decodes a text string with encodeURI() |
| decodeURIComponent() | Decodes a text string with encodeURIComponent() |
Examples: Tutorial2BuiltInFunctionEx1.html
Traditional object-oriented programming languages, such as C++ and Java, create objects through which you access variables and functions. Objects are based on classes. In object-oriented programming, variables, functions, and statements are contained a structure known as a class. Objects are instances of classes and inherit all the class's variables, functions, and statements; you do not access a class directly. Objects can also be based on other objects. Objects based on another class or object are said to descend from the object. Similarly, a class or object from which an object descends is called an ancestor class or object. When you base an object on, or declare an object from, a class or other object, you are said to be instantiating an object.
JavaScript is not truly object-oriented because you cannot create real classes. Instead, you base new JavaScript objects on custom functions, called construction function. You can also have objects in your program on several built-in JavaScript objects. For these reasons, JavaScript is said to be an object-based programming language.
Custom JavaScript Objects are based on functions called constructor functions. A function that is used as the basis for an object is called an object definition, or a constructor function. When you create a new object from a constructor function, you are said to be instantiating a new object or extending the old object. As with the inheritance found in traditional class-based objects, JavaScript objects inherit all the variables and statements of the constructor function on which they are based. Any JavaScript function can serve as a constructor.
Constructor functions have two types of elements:
properties and methods. A property is a variable within a constructor
function. These variables, or properties (fields), are considered to be the data
of any objects that are created from the constructor function. A method
is a function--whether a built-in JavaScript function or a function you
create--that is called from within an object. Object methods are
functions associated with a particular object. When you create a function that
will be used as an object method, you use the this reference in the same
manner as you do when creating a constructor function. After a method is
created, it must be added to the constructor function, using the syntax
this.methodName = function Name; The methodName following the this
reference is the name that is being assigned to the function within the object.
Be sure not to include the parentheses following the function name, as you would
when calling a function in JavaScript.
Example: Tutorial2ObjectEx1.html
<HTML>
<HEAD>
<TITLE>Tutorial 2: Object Example 1: add
function</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function Animal(type, sound, transport_mode) { // constructor function Animal
this.animal_type = type; // dog,
cat, etc.
this.animal_sound = sound;
//woof, meow, etc.
this.animal_transport_mode =
transport_mode;
this.animal_print_it = print_it;
// print_it method
}
function print_it() { // object method print_it
document.writeln("Animal type: " + this.animal_type
+ "<BR>");
document.writeln("Animal sound: " +
this.animal_sound + "<BR>");
document.writeln("Animal
transport_mode: " + this.animal_transport_mode +
"<BR><BR>");
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
pet1 = new Animal("dog", "woof", "walk/run");
pet2 = new Animal("cat", "meow", "walk/run");
pet1.animal_print_it();
pet2.animal_print_it();
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</BODY>
</HTML>
Click here
to see the output of Tutorial2ObjectEx1.html.
The this keyword refers to the current object that
called the constructor function. The three statements assign the three
arguments, type, sound, and transport_mode, to the animal_type, animal_sound,
and animal_transport_mode properties (which are variables) of whichever object (this)
is instantiated from the constructor function. The use of the this
reference is one of the primary differences between standard functions and
constructor functions. Common practice: standard function name starts with a
lowercase letter, and constructor function name starts with an uppercase letter.
Objects are created from constructor functions using the new keyword.
Objects inherit the properties and methods of the constructor functions from which they are instantiated. After instantiating a new object, you can assign additional properties to the object, using a period. Example:
cat = new Animal("feline", "meow", "walk/run");
cat.size = "fat";
When you add a new property to an object that has been extended from a constructor function, the new property is only available to that specific object; the property is not available to the constructor function or to any other objects that were extended from the same constructor function.
When you use the prototype property, any new properties you create will also be available to the constructor function and any objects that extend it. The prototype property is a built-in property that specifies the constructor from which an object was extended. Example:
cat = new Animal("feline", "meow", "walk/run");
Animal.prototype.size = "fat";
To extend one object definition from another object definition, you use the prototype property, followed by the new keyword and the name of the constructor function for the object definition to extend. Example:
function WildAnimal(home, food) {
this.habitat = home; // jungle, desert, ocean
this.diet = food; //carnivore, vegetarian, omnivore
}
WildAnimal.prototype = new Animal();
Some object-oriented programming languages allow objects to inherit from more than one object definition. JavaScript, however, allows objects to inherit from only a single object definition.
| Built-in JavaScript objects | |
|---|---|
| Object | Description |
| Array | Creates new array objects |
| Boolean | Creates new Boolean objects |
| Date | Retrieves and manipulates dates and times |
| Error | Returns run-time error information |
| Function | Creates new function objects |
| Global | Represents the JavaScript built-in methods |
| Math | Contains method and properties for performing mathematical calculations |
| Number | Contains method and properties for manipulating numbers |
| Object | Provides common functionality to all built-in JavaScript objects |
| RegExp | Contains properties for finding and replacing in text strings |
| String | Contains methods and properties for manipulating text strings |
| HTML Elements and Associated JavaScript Events | ||
|---|---|---|
| Element | Description | Event - Event Triggered When |
| <A>...</A> | Link | onClick - An anchor is clicked once onMouseOver - The mouse moves over an anchor onMouseOut - The mouse moves off an anchor |
| <IMG> | Image | onAbort - The loading of an image is interrupted onClick - An image is clicked once onError - There is an error when loading an image onLoad - An image loads onMouseOver - The mouse moves over an image onMouseOut - The mouse moves off an image |
| <AREA> | Area |
onClick - An area is clicked once onMouseOver - The mouse moves over an area onMouseOut - The mouse moves off an area |
| <BODY>...</BODY> | Document body | onBlur - A document becomes inactive onError - There is an error when loading a document onFocus - A document becomes active onLoad - A document loads onUnload - A document unloads |
| <FRAMESET>...</FRAMESET> | Frame Set | onBlur - A frameset becomes inactive onError - There is an error when loading a frameset onFocus - A frameset becomes active onLoad - A frameset loads onUnload - A frameset unloads |
| <FRAME>...</FRAME> | Frame | onBlur - A frame becomes inactive onFocus - A frame becomes active |
| <FORM>...</FORM> | Form | onSubmit - A user submits a form onReset - A form resets |
| <INPUT TYPE='button'> | Box button | onClick - A box button is clicked once |
| <INPUT TYPE='checkbox'> | Check box | onClick - A check box is clicked once |
| <INPUT TYPE='radio'> | Radio button | onClick - A radio button is clicked once |
| <INPUT TYPE='reset'> | Reset button | onClick - A reset button is clicked once |
| <INPUT TYPE='submit'> | Submit button | onClick - A submit button is clicked once |
| <INPUT TYPE='password'> | Password text field | N/A |
| <INPUT TYPE='text'> | Text field | onBlur - A text field becomes inactive onChange - The value of a text field changes onFocus - A text field becomes active onSelect - A user selects a text field in a form |
| <SELECT>...</SELECT> | Selection | onBlur - A selection becomes inactive onChange - The value of a selection changes onFocus - A selection becomes active |
| <TEXTAREA>...</TEXTAREA> | Text Area | onBlur - A text area becomes inactive onChange - The value of a text area changes onFocus - A text area becomes active onSelect - A user selects a text in a form |
Click here to see all the event examples. Details of some JavaScript methods and events are explained below.
Code that executes in response to a specific event is called an event handler. Event handlers are part of an HTML tag. They are not case-sensitive. Therefore, you could write the name of onClick event handler as ONCLICK, onclick, or ONclick. However, capitalizing only the first letter of the event name itself is a standard convention.
The JavaScript code for an event handler is contained within the quotation marks following the name of the JavaScript event handler.
The alert() method displays a pop-up dialog box with an OK button. Syntax: alert(message);.
The prompt() method displays a dialog box with a message, a text box, an OK button, and a Cancel button. Any text that is entered into a prompt() method text box by a user can be assigned to a variable, if the user presses the OK button. No value is assigned if the user presses the Cancel button. Syntax variable_name = prompt(message, default_text);.
The confirm() method displays a dialog box that contains a Cancel button as well as an OK button. When the user clicks the OK button in the confirm dialog box, a value of true is returned. When the user clicks the Cancel button in the confirm dialog box, a value of false is returned. Syntax: return_boolean_variable = confirm(message);
To make your custom message appear in the status bar, use the JavaScript status property. Syntax: status = "text";. For older browsers, the syntax is window.status = "text";.
You can also use the defaultStatus property within a <SCRIPT>...</SCRIPT> tag pair to specify the default text that appears in the status bar whenever the mouse is not positioned over a link. Syntax: defaultStatus = "Text";. Note that the defaultStatus property overrides any text specified by an onMouseOut event handler.
When you override an internal event handler with your own code, you must return a value of true or false, using the return statement. With the <A> tag and the onClick event, a value of true indicates that you want the Web browser to perform its default event handling operation of opening the URL referenced in the link. A value of false indicates that you do not want the <A> tag to perform its default event handling operation. Unlike the return value for the onClick event handler, a return value of true from the onMouseOver event handler tells the Web browser not to perform its own event handling routine of displaying the name of the link's URL in the status bar. In constrast, the onMouseOut event handler returns a value of false to prevent the Web browser from performing its default event handling routine of displaying the value assigned to the defaultStatus property (if any) in the status bar.