Encyclopedia
|
|
JavaScript syntax
The syntax of JavaScript is a set of rules that defines what constitutes a valid program in the Javascript language.
Origin of SyntaxBrendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification as follows: VariablesVariables in standard JavaScript have no type attached, and any value can be stored in any variable. Variables can be declared with a Basic data typesNumbersNumbers in JavaScript are represented in binary as IEEE-754 Doubles, which provides an accuracy to about 14 or 15 significant digits JavaScript FAQ 4.7. Because they are binary numbers, they do not always exactly represent decimal numbers, particularly fractions. This becomes an issue when formatting numbers for output, which JavaScript has no built-in methods for. For example: As a result, rounding should be used whenever numbers are formatted for output. The toFixed() method is not part of the ECMAScript specification and is implemented differently in various environments, so it can't be relied upon. Numbers may be specified in any of these notations: In some ECMAScript implementations such as ActionScript, RGB color values are sometimes specified with hexadecimal integers: The Number constructor may be used to perform explicit numeric conversion: When used as a constructor, a numeric wrapper object is created, (though it is of little use): ArraysAn Array is a map from integers to values. In JavaScript, all objects can map from integers to values, but
Arrays are a special type of object that has extra behavior and methods specializing in integer indices (e.g., Arrays have a Elements of Arrays may be accessed using normal object property access notation: The above two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number: Declaration of an array can use either an Array literal or the Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". Setting You can use the object declaration literal to create objects that behave much like associative arrays in other languages: You can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both. StringsStrings in Javascript are a sequence of characters. Strings in JavaScript can be created directly by placing the series of characters between double or single quotes. In Mozilla based browsers, individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays: But, for Internet Explorer, you have to access the individual characters using the charAt() method (provided by String class). This is the preferred way when accessing individual characters within a string, as it also works in Mozilla based browsers: however, JavaScript strings are immutable: Applying the equality operator ("==") to two strings returns true if the strings have the same contents, which means: of same length and same cases (for alphabets). Thus: ObjectsThe most basic objects in JavaScript act as dictionaries. These dictionaries can have any type of value paired with a key, which is a string. Objects with values can be created directly through object literal notation: Properties of objects can be created, set, and read individually using the familiar dot ('.') notation or by a similar syntax to arrays: Object literals and array literals allow one to easily create flexible data structures: This is the basis for JSON, which is a simple notation that uses JavaScript-like syntax for data exchange. OperatorsThe '+' operator is overloaded; it is used for string concatenation and arithmetic addition and also to convert strings to numbers. It also has special meaning when used in a regular expression. ArithmeticBinary operators + Addition - Subtraction * Multiplication / Division (returns a floating-point value) % Modulus (returns the integer remainder) Unary operators - Unary negation (reverses the sign) ++ Increment (can be prefix or postfix) -- Decrement (can be prefix or postfix) Assignment= Assign += Add and assign -= Subtract and assign *= Multiply and assign /= Divide and assign %= Modulus and assign Comparison== Equal != Not equal > Greater than >= Greater than or equal to < Less than <= Less than or equal to === Identical (equal and of the same type) !== Not identical BooleanJavaScript has three logical boolean operators: && (logical AND), || (logical OR), and ! (logical NOT). In the context of a boolean operation, all JavaScript values evaluate to true unless the value is the boolean false itself, the number 0, a string of length 0, or one of the special values null, undefined, or NaN. The Boolean function can be used to explicitly perform this conversion: The unary NOT operator ! first evaluates its operand in a boolean context, and then returns the opposite boolean value: A double use of the ! operator can be used to normalize a boolean value: In the earliest implementations of JavaScript and JScript, the && and || operators behaved in the same manner as their counterparts in other C derived programming languages, in that they always returned a boolean value: In the newer implementations, these operators return one of their operands: This novel behavior is little known even among experienced JavaScripters, and can cause problems if one expects an actual boolean value.
a || b is automatically true if a is true. There is no reason to evaluate b. a && b is false if a is false. There is no reason to evaluate b. && and || or ! not (logical negation) BitwiseBinary operators
& And
| Or
^ Xor
<< Shift left (zero fill)
>> Shift right (sign-propagating); copies of the leftmost bit (sign bit) are shifted in from the
left.
>>> Shift right (zero fill)
For positive numbers, >> and >>> yield the same result.
Unary operators ~ Not (inverts the bits) String= Assignment + Concatenation += Concatenate and assign Examples Control structuresIf ... elseif (expr)
{
statements;
}
else if (expr)
{
statements;
}
else
{
statements;
}
Conditional operatorInstead of using "if(){...}else{...}", a shorter syntax can be used: var result = (param == condition) ? statement : otherwise; is the same as: if (param == condition)
{
result = statement;
}
else
{
result= otherwise;
}
Switch statementswitch (expr) {
case VALUE:
statements;
break;
case VALUE:
statements;
break;
default:
statements;
break;
}
For loopfor (initial-expr; cond-expr; expr evaluated after each loopround) {
statements;
}
For ... in loopfor (var property-name in object-name) {
statements using object-name[property-name];
}
While loopwhile (cond-expr) {
statements;
}
Do ... whiledo {
statements;
} while (cond-expr);
Withwith(document) {
var a = getElementById('a');
var b = getElementById('b');
var c = getElementById('c');
};
FunctionsA function is a block with a (possibly empty) parameter list that is normally given a name. A function may give back a return value. function function-name(arg1, arg2, arg3) {
statements;
return expression;
}
Anonymous functions are also possible: var fn = function(arg1, arg2) {
statements;
return expression;
};
Example: Euclid's original algorithm of finding the greatest common divisor. (This is a geometrical solution which subtracts the shorter segment from the longer): The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value Basic data types (strings, integers, ...) are passed by value whereas objects are passed by reference. ObjectsFor convenience, Types are normally subdivided into primitives and objects. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values, ("slots" in prototype-based programming terminology). JavaScript objects are often mistakenly described as associative arrays or hashes, but they are neither. JavaScript has several kinds of built-in objects, namely Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Other objects are "host objects", defined not by the language but by the runtime environment. For example, in a browser, typical host objects belong to the DOM (window, form, links etc.). Creating objectsObjects can be created using a declaration, an initialiser or a constructor function: ConstructorsConstructor functions are a way to create multiple instances or copies of the same object. JavaScript is a prototype based object-based language. This means that inheritance is between objects, not between classes (JavaScript has no classes). Objects inherit properties from their prototypes. Properties and methods can be added by the constructor, or they can be added and removed after the object has been created. To do this for all instances created by a single constructor function, the Example: Manipulating an object InheritanceJavaScript supports inheritance hierarchies through prototyping. For example: (note: this example makes liberal use of the way methods and properties of objects are the same, called "slots" in Prototype-based programming) will result in the display: Derive::Override() Base::BaseFunction() Another way to implement the override method is: ExceptionsNewer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a The Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. Once the catch block finishes, or the try block finishes with no exceptions thrown, then the statements in the finally block execute. This is generally used to free memory that may be lost if a fatal error occurs—though this is less of a concern in JavaScript. This figure summarizes the operation of a try...catch...finally statement: The try {
statements
}
catch (err) {
// handle errors
}
In fact, the try {
statements
}
finally {
// ignore potential errors and just go directly to finally
}
Note that at least one of catch and finally are required. It is an error to simply use the try block alone, even if you don't need to handle the error: try { statement; } // ERROR
The catch argument is also required, even if you don't need to use it: try { statement; } catch( ) { statement; } // ERROR
The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in Java: MiscellaneousCase sensitivityJavaScript is case sensitive. It is common to start object names with a capitalised letter and functions or variables with a lower-case letter. Whitespace and semicolonsSpaces, tabs and newlines used outside of string constants are called whitespace. Unlike C, whitespace in JavaScript source can directly impact semantics. Because of a technique called "semicolon insertion", any statement that is well formed when a newline is parsed will be considered complete (as if a semicolon were inserted just prior to the newline). Programmers are advised to supply statement terminating semicolons explicitly to enhance readability and lessen unintended effects of the automatic semicolon insertion. Unnecessary whitespace, whitespace characters that are not needed for correct syntax, can increase the amount of wasted space, and therefore the file size of .js files. The easiest way to address the problem of file size is to set the server to use zip compression. This compression will work far better than any whitespace parser and will reduce the size of all other source your server uploads. This method will work with or without semi-colons. CommentsComment syntax is the same as in C++. See alsoReferences
External linksReference MaterialResources
Source: Wikipedia | The above article is available under the GNU FDL. | Edit this article
|
Advertisement |
top
©2006-2007 TutorGig.com. All Rights Reserved. Privacy Statement