FACTOID # 116: France is the top destination in the world for tourists, accounting for 11 percent of all tourist arrivals worldwide.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

Encyclopedia > JavaScript syntax

The syntax of JavaScript is a set of rules that defines how a JavaScript program will be written and interpreted. The JavaScript syntax was influenced by several programming languages, including Java. JavaScript is the name of Netscape Communications Corporations implementation of the ECMAScript standard, a scripting language based on the concept of prototype-based programming. ... An interpreter is a computer program that executes other programs. ... Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. ...

Contents

Origin of Syntax

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

JavaScript borrows most of its syntax from Java, but also inherits from Awk and Perl, with some indirect influence from Self in its object prototype system.

Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. ... AWK is a general purpose computer language that is designed for processing text based data, either in files or data streams. ... Perl, also Practical Extraction and Report Language (a backronym, see below) is a dynamic procedural programming language designed by Larry Wall and first released in 1987. ... This article or section does not cite its references or sources. ...

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 used without being declared with 'var', are global (can be used by the entire program). In computer science and mathematics, a variable (sometimes called a pronumeral) is a symbol denoting a quantity or symbolic representation. ... In computer science and mathematics, a variable (sometimes called a pronumeral) is a symbol denoting a quantity or symbolic representation. ...


Here is an example of variable declarations and global values:

 x = 0; // A global variable var y = 'Hello!'; // Another global variable function f(){ var z = 'foxes'; // A local variable twenty = 20; // Another local return x; // We can use x here because it is global } // The value of z is no longer available 

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:

 alert(0.94 - 0.01); // displays 0.9299999999999999 

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. ECMAScript is a scripting programming language, standardized by Ecma International in the ECMA-262 specification. ...


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). In computer programming, a group of homogeneous elements of a specific data type is known as an array, one of the simplest data structures. ...


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:

 myArray[1] myArray["1"] 

The above two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number:

 myArray.1 (syntax error) myArray["01"] (not the same as myArray[1]) 

Declaration of an array can use either an Array literal or the Array constructor:

 myArray = [0,1,,,4,5]; (array with length 6 and 4 elements) myArray = new Array(0,1,2,3,4,5); (array with length 6 and 6 elements) myArray = new Array(365); (an empty array with length 365) 

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. In computer programming, a group of homogeneous elements of a specific data type is known as an array, one of the simplest data structures. ... A sparse array in computing is an array where most of the elements have the same value (called the default value -- usually 0) and only a few elements have a non-default value. ...


You can use the object declaration literal to create objects that behave much like associative arrays in other languages:

 dog = {"color":"brown", "size":"large"}; dog["color"]; (this gives you "brown") 

You can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both.

 cats = [{"color":"brown", "size":"large"}, {"color":"black", "size":"small"}]; cats[0]["size"]; (this gives you "large") dogs = {"rover":{"color":"brown", "size":"large"}, "spot":{"color":"black", "size":"small"}}; dogs["spot"]["size"]; (this gives you "small") 

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.

 var greeting = "Hello, ronald!"; var another_greeting = 'Greetings, people of Earth.'; 

Individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays:

 var h = greeting[0]; // Now h contains 'H' 

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:

 var o = {name: 'My Object', purpose: 'This object is utterly without purpose.', answer: 42}; 

Properties of objects can be created, set, and read individually using the familiar dot ('.') notation or by a similar syntax to arrays:

 var name = o.name; // name now contains 'My Object' var answer = o['answer']; // answer now contains 42 

Object literals and array literals allow one to easily create flexible data structures:

 var myStructure = { name: { first: "Mel", last: "Smith" }, age: 33, hobbies: [ "chess", "jogging" ] }; 

This is the basis for JSON, which is a simple notation that uses JavaScript-like syntax for data exchange. JSON (pronounced as IPA , or like the English given name Jason), which stands for JavaScript Object Notation, is a lightweight computer data interchange format. ...


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. In computer programming, operator overloading (less commonly known as operator ad-hoc polymorphism) is a specific case of polymorphism in which some or all of operators like +, = or == have different implementations depending on the types of their arguments. ... In computing, a regular expression (abbreviated as regexp or regex, with plural forms regexps, regexes, or regexen) is a string that describes or matches a set of strings, according to certain syntax rules. ...

 // Concatenate 2 strings var a = 'This'; var b = ' and that'; alert(a + b); // displays 'This and that' // Add two numbers var x = 2; var y = 6; alert(x + y); // displays 8 // Adding a number and a string results in concatenation alert( x + '2'); // displays 22 // Convert a string to a number var z = '4'; // z is a string (the digit 4) alert( z + x) // displays 42 alert( +z + x) // displays 6 

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 

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

  • 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

 str = "ab" + "cd"; // "abcd" str += "e"; // "abcde" 

Control structures

If ... else

 if (expr) { statements; } else if (expr) { statements; } else { statements; } 
  • else statements must be cuddled (i.e. "} else {" , all on the same line), or else some browsers may not parse them correctly.

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.

In computer science control flow (or alternatively, flow of control) refers to the order in which the individual statements or instructions of an imperative program are performed or executed. ...

For loop

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

It has been suggested that Foreach be merged into this article or section. ...

For ... in loop

 for (var property-name in object-name) { statements using object-name[property-name]; } 
  • Iterates through all enumerable properties of an object, or the objects at all indices of an array.

While loop

 while (cond-expr) { statements; } 

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. ...

Do ... while

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

In most computer programming languages, a do while loop is a control structure that allows code to be executed repeatedly based on a given Boolean condition. ...

Functions

A function is a block with a (possibly empty) argument list that is normally given a name. A function may give back a return value. In computer science, a subroutine (function, procedure, or subprogram) is a sequence of code which performs a specific task, as part of a larger program, and is grouped as one, or more, statement blocks; such code is sometimes collected into software libraries. ...

 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 Euclidean algorithm (also called Euclids algorithm) is an algorithm to determine the greatest common divisor (gcd) of two integers. ...

 function gcd(segmentA, segmentB) { while (segmentA != segmentB) { if (segmentA > segmentB) segmentA -= segmentB; else segmentB -= segmentA; } return segmentA; } 

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 (which is an array); this provides access to all arguments using indices (e.g. arguments[0], arguments[1], ... arguments[n]), including those beyond the number of named arguments.


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. Prototype-based programming is a style of object-oriented programming in which classes are not present, and behaviour reuse (known as inheritance in class-based languages) is accomplished through a process of cloning existing objects which serve as prototypes. ... In computing, an associative array, also known as a map, lookup table, or dictionary, is an abstract data type very closely related to the mathematical concept of a function with a finite domain. ...


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.). In computer programming, a group of homogeneous elements of a specific data type is known as an array, one of the simplest data structures. ... In computer science the boolean datatype, sometimes called the logical datatype, is a primitive datatype having two values: one and zero (sometimes called true and false). ... Note that this article includes some hyperlinked dates whose format is configurable in Special pages | Preferences. What you see may not be what the author intended. ... In computer science, a subroutine (function, procedure, or subprogram) is a sequence of code which performs a specific task, as part of a larger program, and is grouped as one, or more, statement blocks; such code is sometimes collected into software libraries. ... Euclid, Greek mathematician, 3rd century BC, known today as the father of geometry; shown here in a detail of The School of Athens by Raphael. ... A number is an abstract entity that represents a count or measurement. ... In strictly mathematical branches of computer science the term object is used in a purely mathematical sense to refer to any thing. While this interpretation is useful in the discussion of abstract theory, it is not concrete enough to serve as a primitive datatype in the discussion of more concrete... A regular expression (abbreviated as regexp, regex or regxp) is a string that describes or matches a set of strings, according to certain syntax rules. ... In computer programming and some branches of mathematics, strings are sequences of various simple objects. ... An example of a graphical user interface in Windows XP, with the My Music window displayed In computing, a window is a visual area, usually rectangular in shape, containing some kind of user interface, displaying the output of and allowing input for one of a number of simultaneously running computer... This article is about the word form meaning a type of document. ... A hyperlink (often referred to as simply a link), is a reference or navigation element in a document to another section of the same document, another document, or a specified section of another document, that automatically brings the referred information to the user when the navigation element is selected by...


Creating objects

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

 // Declaration var anObject = new Object(); // Initialiser var objectA = {}; var objectB = {'index1':'value 1','index2':'value 2'}; // Constructor (see below) 

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. A constructor function, in computer programming, is a member function of a class used to create an object instance of a particular class and possibly also populate some or all of that object instances attributes. ... Prototype-based programming is a style of object-oriented programming in which classes are not present, and behaviour reuse (known as inheritance in class-based languages) is accomplished through a process of cloning existing objects which serve as 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. In computer science, garbage collection (also known as GC) is a form of automatic memory management. ...


Example: Manipulating an object

 // constructor function function MyObject(attributeA, attributeB) { this.attributeA = attributeA; this.attributeB = attributeB; } // create an Object obj = new MyObject('red', 1000); // access an attribute of obj alert(obj.attributeA); // access an attribute using square bracket notation alert(obj["attributeA"]); // add a new property obj.attributeC = new Date(); // remove a property of obj delete obj.attributeB; // remove the whole Object delete obj; 

Inheritance

JavaScript supports inheritance hierarchies through prototyping. For example:

 function Base() { this.Override = function() { alert("Base::Override()"); } this.BaseFunction = function() { alert("Base::BaseFunction()"); } } function Derive() { this.Override = function() { alert("Derive::Override()"); } } Derive.prototype = new Base(); d = new Derive(); d.Override(); d.BaseFunction(); d.__proto__.Override(); // mozilla only 

will result in the display:

 Derive::Override() Base::BaseFunction() Base::Override() // mozilla only 

Exceptions

Newer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a try ... catch ... finally exception handling statement. Purloined from the Java programming language, this is intended to help handling run-time errors. Windows Internet Explorer, previously Internet Explorer, abbreviated IE, or MSIE[1], is a graphical web browser developed by Microsoft and included as part of the Microsoft Windows line of operating systems. ... Netscape was a proprietary cross-platform Internet suite created by Netscape Communications Corporation and then in-house by AOL to continue the Netscape series after Netscape 6. ... Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. ... Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. ...


The try ... catch ... finally statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows: Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. ...

 try { // Statements in which exceptions might be thrown } catch(error) { // Statements that execute in the event of an exception } finally { // Statements that execute afterward either way } 

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:

 try { // Create an array arr = new Array(); // Call a function that may not succeed func(arr); } catch (...) { // Recover from error logError(); } finally { // Even if a fatal error occurred, we can still free our array delete arr; } 

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 } 

Miscellaneous

Case sensitivity

JavaScript is case sensitive.


Whitespace

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. A space is a punctuation convention for providing interword separation in some scripts, including the Latin, Greek, Cyrillic, and Arabic. ... Tab may refer to: The tab key, used to indent text to a preset horizontal position. ... In computing, a newline is a special character or sequence of characters signifying the end of a line of text. ... For information on the programming language Whitespace, see Whitespace programming language. ...


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, but they should be used anyway for readability.


Comments

Comment syntax is the same as in C++. In computer programming, a comment is a programming language construct that provides a mechanism for embedding information in the source code that is (generally) ignored by compilers and interpreters but may be of use to people reading the program source, or other programming tools that process the source such as... C++ (generally pronounced /si plÊŒs plÊŒs/) is a general-purpose, high-level programming language with low-level facilities. ...

 // comment 
 /* multi-line comment */ 

See also

JavaScript is the name of Netscape Communications Corporations implementation of the ECMAScript standard, a scripting language based on the concept of prototype-based programming. ...

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

External links

Reference Material

  • Core References for JavaScript versions 1.5, 1.4, 1.3 and 1.2
Wikibooks has a book on the topic of

Image File history File links Wikibooks-logo-en. ... Wikibooks logo Wikibooks, previously called Wikimedia Free Textbook Project and Wikimedia-Textbooks, is part of the Wikimedia Foundation. ...

Resources


 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your location
Your comments
Please enter the 5-letter protection code


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.