Computer Basic Training

Computer Fundamentals

Dos-Disk Operating System

Windows - 98

Windows - Xp

Shortkeys

Computer Basic

Internet

Designing

HTML - hyper text transfer protocol

File Transfer Protocol

Computer Virus

Foxpro

Javascript

Career

Tools

Ecommerce

Computer Glossary

 


Javascript

Introduction:

This JavaScript tutorial is aimed primarily at those who have had at least some exposure to another programming language. It is not our purpose here to cover the basic concepts of computer programming, but rather illustrate the syntax and methodology of JavaScript. For its part, JavaScript is a rather basic language, which conforms tightly to the core concepts -of computer programming. Any background in programming, from Visual Basic to Pascal to C (which is far more advanced) is sufficient to readily understanding JavaScript.

Those who are true novices at programming would be better off with any number of available books on JavaScript which take the time to explain both the specifics of the language and programming concepts in general.

Embedding JavaScript
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="JavaScript l.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 Grammar
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 P[;'V-O 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 and Data Types :
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=l; total=0;
...additional statements...

In the example above, the variable loop will be local to new Function (), 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 Ox (or OX) 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.)

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: 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 ofx following the increment whereas x++ will return the value ofx 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 ofx following the decrement whereas x— will return the value otx 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:

(also -=, *=, /=)
&= (also |=)
Example: total=(price+tax+shipping)
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)
Assigns result of (lefthand operand && righthand operand) to lefthand
operand.


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.


Statements
Statements define the flow of a script, known as "program flow." A statement, like a fully grammatical English sentence, is made up of smaller expressions which, altogether, evaluate into a cogent meaning. In JavaScript, statements are organized as either conditionals, loops, object manipulations, and comments.

Good practice suggests that each JavaScript statements should be terminated with a semicolon (;). This is often not strictly necessary, as a new line also serves to separate statements, but when multiple statements reside on the same line the semicolon delimiter is mandatory.

A set of statements that is surrounded by braces is called a block. Blocks of statements are used, for example, in functions and conditionals.

Normally statements are executed sequentially: x = 1; y = 2; z = x + y; but this can be altered by some statements which test a condition and branch or loop according to the result.

Conditionals
Conditional statements direct program flow in specified directions depending upon the outcomes of specified conditions. These tests are a major influence on the order of execution in a program.
if—else
As seen in many programming languages, if the condition evaluates to true then the block of statements 1 it pvftp.nted. Ontionallv. an else clause specifies a block of statements! which are executed otherwise.
Vignesh Computer Education
You may omit the else clause if there are no statements which need to be executed if the condition is false. .
if (condition) { statements!; }
else { statements2; }

Switch (Netscape & MSIE 4)
Commonly known as a "case statement," switch matches an expression with a specified case, and executes the statements defined for that case. In essence, the switch statement is a sort of shorthand for combining many implied if statements together.
switch (expression){ case label :
statement;
break;
case label :
statement;
break;
default : statement;
}

For example, imagine that you wanted to execute different sets of statements depending on whether favoritePet was "dog," "cat," or "iguana." Note that the break; statement prevents any cases below the match from being executed. The default case is matched if none of the cases match the expression.
Switch(favoritePet){ case "dog" :
statements;
break;
case "cat" :
statements;
break;
case "iguana" :
statements;
break;
default : statements;
}


NEXT

Our Featured Links :

 

Copyright © 2006 Vignesh.in Computer Services. All rights reserved.