JavaScript syntax
JavaScript syntax in TutorGig Encyclopedia Encyclopedia
        Search: in
  Tutorials     Encyclopedia     Dictionary     Web     Store     Directory  
 
JavaScript_syntax Email this to a friend      JavaScript_syntax

JavaScript syntax

The syntax of JavaScript is a set of rules that defines what constitutes a valid program in the Javascript language.

Contents


Origin of Syntax

Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification as follows:

Variables

Variables in standard JavaScript have no type attached, and any value can be stored in any variable. Variables can be declared with a var statement. These variables are lexically scoped and once a variable is declared, it may be accessed anywhere inside the function where it is declared. Variables declared outside any function, and variables first used within functions without being declared with 'var', are global. Here is an example of variable declarations and global values:

Basic data types

Numbers

Numbers 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):

Arrays

An 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., join, slice, and push).

Arrays have a length property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated if one creates a property with an even larger index. Writing a smaller number to the length property will remove larger indices. This length property is the only special feature of Arrays that distinguishes it from other objects.

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 Array constructor:

Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". Setting myArray[10] = 'someThing' and myArray[57] = 'somethingOther' only uses space for these two elements, just like any other object. The length of the array will still be reported as 58.

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.

Strings

Strings 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:

Objects

The 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.

Operators

The '+' 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.

Arithmetic

Binary 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

Boolean

JavaScript 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.

  • Short-circuit logical operations means the expression will be evaluated from left to right until the answer can be determined. For example:

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)

Bitwise

Binary 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 structures

If ... else

if (expr)
{
  statements;
}
else if (expr)
{
  statements;
}
else
{
  statements;
}



Conditional operator

Instead 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 statement

switch (expr) {
  case VALUE: 
    statements;
    break;
  case VALUE: 
    statements;
    break;
  default:
    statements;
    break;
}

  • break; is optional; however, it's recommended to use it in most cases, since otherwise code execution will continue to the body of the next case block.
  • Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
  • Strings can be used for the case values.
  • Braces are required.

For loop

for (initial-expr; cond-expr; expr evaluated after each loopround) {
  statements;
}

For ... in loop

for (var property-name in object-name) {
  statements using object-name[property-name];
}

  • Iterates through all enumerable properties of an object.
  • Not usable for arrays. It would iterate not only through the array indices, but also through other visible properties.
  • There are differences between the various web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice each browser returns a slightly different set of properties during introspection.

While loop

while (cond-expr) {
  statements;
}

Do ... while

do {
  statements;
} while (cond-expr);

With

with(document) {
  var a = getElementById('a');
  var b = getElementById('b');
  var c = getElementById('c');
};
  • Note the absence of document. before each getElementById() invocation.

Functions

A 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 undefined. Within the function the arguments may also be accessed through the arguments list; this provides access to all arguments using indices (e.g. arguments[0], arguments[1], ... arguments[n]), including those beyond the number of named arguments. Note that while the arguments list has a .length property, it is not an instance of Array; it does not have methods such as .slice(), .sort(), etc.

Basic data types (strings, integers, ...) are passed by value whereas objects are passed by reference.

Objects

For 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 objects

Objects can be created using a declaration, an initialiser or a constructor function:

Constructors

Constructor 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 prototype property of the constructor is used to access the prototype object. Object deletion is not mandatory as the scripting engine will garbage collect any variables that are no longer being referenced.

Example: Manipulating an object

Inheritance

JavaScript 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:

Exceptions

Newer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a try ... catch ... finally exception handling statement to handle run-time errors.

The try ... catch ... finally statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:

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 finally part may be omitted:

try {
  statements
}
catch (err) {
  // handle errors
}

In fact, the catch part may also be omitted:

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:

Miscellaneous

Case sensitivity

JavaScript 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 semicolons

Spaces, 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.

Comments

Comment syntax is the same as in C++.

See also

References

  • David Flanagan, Paula Ferguson: JavaScript: The Definitive Guide, O'Reilly & Associates, ISBN 0-596-10199-6
  • Danny Goodman, Brendan Eich: JavaScript Bible, Wiley, John & Sons, ISBN 0-7645-3342-8
  • Thomas A. Powell, Fritz Schneider: JavaScript: The Complete Reference, McGraw-Hill Companies, ISBN 0-07-219127-9
  • Emily Vander Veer: JavaScript For Dummies, 4th Edition, Wiley, ISBN 0-7645-7659-3
  • Kevin Applesauce: JavaScript Syntax,KND publishers, ISBN 0-213-26453-8

External links

Reference Material

  • Core References for JavaScript versions 1.5, 1.4, 1.3 and 1.2

Resources

fr:Syntaxe JavaScript





Source: Wikipedia | The above article is available under the GNU FDL. | Edit this article



Related Links in JavaScript syntax

Search the web for JavaScript syntax
Search for tutorials in JavaScript syntax
Search Encyclopedia for JavaScript syntax
Search for JavaScript syntax in TutorGig Dictionary
Search for JavaScript syntax in Open Directory
Search for JavaScript syntax in TutorGig Store
Search for JavaScript syntax in PriceGig



Help build the largest human-edited directory on the web.
Submit a Site - Open Directory Project - Become an Editor
Related links are provided by Open Directory Project.

Advertisement


JavaScript syntax in TutorGig Encyclopedia
JavaScript_syntax top JavaScript_syntax

Home - Add TutorGig to Your Site - Disclaimer

©2006-2007 TutorGig.com. All Rights Reserved. Privacy Statement